【问题标题】:how can i find alternating 1 and 0 using REGEX如何使用 REGEX 找到交替的 1 和 0
【发布时间】:2021-07-31 21:31:24
【问题描述】:

问题是找到所有在 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]

【问题讨论】:

    标签: java regex regex-lookarounds


    【解决方案1】:

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

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

    模式匹配:

    • \b 防止部分匹配的单词边界
    • (?&gt;原子团
      • 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
    

    【讨论】:

      【解决方案2】:

      你可以使用

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

      请参阅regex demo

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

      详情

      • \b - 单词边界
      • (?!\d*(\d)\1) - 当前号码中不允许出现重复的后续数字
      • [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]
      

      【讨论】:

        猜你喜欢
        • 2021-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-09
        • 1970-01-01
        • 2016-10-15
        相关资源
        最近更新 更多