首页 > 解决方案 > 如何使用 REGEX 找到交替的 1 和 0

问题描述

问题是找到所有在 1 和 0 之间交替的位序列,即连续不超过 1 或 0 的位序列,并将其返回到列表中。

到目前为止我做了什么

  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());

它应该返回

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

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

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

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

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

标签: javaregexregex-lookarounds

解决方案


您可以使用

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

请参阅正则表达式演示

在 Java 中,使用"\\b(?!\\d*(\\d)\\1)[10]+\\b".

细节

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

查看Java 演示

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]

推荐阅读