【问题标题】:Regex matching exact instance of special characters正则表达式匹配特殊字符的精确实例
【发布时间】:2014-11-25 13:51:31
【问题描述】:

请原谅再次询问相同的正则表达式问题,但在这里结合所有现有答案并没有给我很好的结果。

在 Java 中(如“aa | bb”.split(myregex))我需要用“|”分割字符串一次其他时间通过“||”。

请注意“|”不能与“||”的外观相匹配或“|||”。例如,“|”的正则表达式不得触摸“aa || bb”。但是“||”的正则表达式应该拆分所有“||”+ 就像“aa || bb”和“aa |||| bb”一样。 我尝试了 \b(?:([\|])(?!\1))+\b 的不同变体,但这对在线正则表达式检查器产生了不好的结果。

请帮忙。与我们分享这两个正则表达式。

问候,

【问题讨论】:

标签: java regex


【解决方案1】:

两次迭代?

result1 = myString.split("[^\\|]\\|[^\\|]"); // result of splitting on |, regex means | not followed by another | or preceded
result2 = result1.split("\\|{2,}"); // result of splitting on | that occurs 2 or more times

不知道你应该如何分割 |-es 的奇数,但如果你只需要偶数:

result2 = result1.split("(\\|\\|)+"); // result of splitting on || that occur any times

也许更具可读性:

String not(String s){
  return "[^" + s + "]";
}
String pipe = "\\|";

result1 = myString.split(not(pipe) + pipe + not(pipe)); 
result2 = result1.split(pipe + "{2,}"); 

【讨论】:

    【解决方案2】:

    怎么样:

    (?:(?<!\\|)\\|(?:\\|)|\\|{2,})
    

    这将匹配一个管道,其前后没有另一个管道或大于或等于 2 的管道数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-10
      • 1970-01-01
      相关资源
      最近更新 更多