我如何使用正则表达式找到交替的 1 和 0

how can i find alternating 1 and 0 using REGEX

问题是找到所有在 1 和 0 之间交替的位序列,即那些连续不超过 1 或 0 且 return 在列表中的位序列。

到目前为止我做了什么

  public static List<String> findBits(String text) {
    Pattern pattern = Pattern.compile("([01])(?!\1)([01])(?:\1\2)*\1?|(?<!\S)[01](?!\S)|1.|0.", Pattern.DOTALL);
    Matcher matcher = pattern.matcher(text);
    return matcher.results()
        .map(String::valueOf)
        .collect(Collectors.toList());

应该return

这里没有二进制数 3434。 -> [] 空列表

嘿,朋友,这是 1。 -> [1]

这些是 1001、1010、1011、1100、1101 -> [1010]

这是一个长值 1010101010,这个也是 1010101010101011 -> [1010101010]

0 + 0 也是 0。 -> [0,0,0]

您可以使用

\b(?!\d*(\d))[10]+\b

参见regex demo

在Java中用"\b(?!\d*(\d)\1)[10]+\b"声明。

详情

  • \b - 单词边界
  • (?!\d*(\d)) - 当前号码中不允许重复后续数字
  • [10]+ - 一个或多个 10 个字符
  • \b - 单词边界

看到一个Java demo:

public static Pattern pattern = Pattern.compile("\b(?!\d*(\d)\1)[10]+\b");
    
public static List<String> findBits(String text) {
    Matcher matcher = pattern.matcher(text);
    return pattern.matcher(text)
        .results()
        .map(MatchResult::group)
        .collect(Collectors.toList()); //.toArray(String[]::new);
}
        
public static void main (String[] args) throws java.lang.Exception
{
    List<String> r = findBits("no binary numbers here 3434. Hey friend this is a 1. Those are 1001, 1010, 1011, 1100, 1101. This is a long value 1010101010 and this one as well 1010101010101011. 0 + 0 is a also a 0.");
    System.out.println(r);
}

// => [1, 1010, 1010101010, 0, 0, 0]

另一种选择是重复 1,然后重复可选的 01,并以可选的零结尾,或者反过来

\b(?>1(?:01)*0?|0(?:10)*1?)\b

模式匹配:

  • \b 防止部分匹配的单词边界
  • (?> 原子团
    • 1(?:01)*0? 匹配 1 可选重复 01 和可选 0
    • |
    • 0(?:10)*1? 匹配 0 可选重复 10 和可选 1
  • ) 关闭捕获组
  • \b一个单词边界

Regex demo | Java demo

例如

public static List<String> findBits(String text) {
    Pattern pattern = Pattern.compile("\b(?>1(?:01)*0?|0(?:10)*1?)\b");
    Matcher matcher = pattern.matcher(text);
    return matcher
        .results().map(MatchResult::group)
        .collect(Collectors.toList());
}

循环结果:

for (String item : findBits("no binary numbers here 3434. Hey friend this is a 1. Those are 1001, 1010, 1011, 1100, 1101. This is a long value 1010101010 and this one as well 1010101010101011. 0 + 0 is a also a 0."))
    System.out.println(item);

输出

1
1010
1010101010
0
0
0