正则表达式,用于匹配三个非连续的数字,其中数字必须为0或1。

huangapple go评论118阅读模式
英文:

Regex to match three non-continuous digits where digits needs to be either 0 or 1

问题

  1. 例如:
  2. 000=true
  3. 111=true
  4. 02010=true
  5. 1011=true
  6. 00101=true
  7. 12001=false
  8. 22200=false
  9. Pattern pattern = Pattern.compile(".*0.*0.*0 || .*1.*1.*1");
  10. Matcher matcher = pattern.matches("00110");
  11. 这个模式会在字符串为"2"的情况下返回true
英文:
  1. For Eg:
  2. 000=true
  3. 111=true
  4. 02010=true
  5. 1011=true
  6. 00101=true
  7. 12001=false
  8. 22200=false
  1. Pattern pattern=Patter.complie(".*0.*0.*0 || .*1.*1.*1");
  2. Matcher matcher=pattern.matches("00110");

This pattern is returning true either my string is "2";

答案1

得分: 4

我会选择:

  1. .*([01])(.*){2}.*

在线演示 中查看。

该正则表达式使用 反向引用 \1 来引用捕获在第1组中的字符进行重复匹配。


根据需要,可以将更多字符添加到字符类中,例如要在允许的列表中包含字符 "2""3",请使用 [0123] 或简单地使用 [0-3]

英文:

I would just go with:

  1. .*([01])(.*){2}.*

See live demo.

The uses a back reference \1 to the character captured in group 1 for the repeat.


Add as many characters to the character class as you like, eg to include the characters "2"and "3" in the allowed list, use [0123], or simply [0-3]

答案2

得分: 1

正则表达式中不存在 || 这样的运算符,只有 |,最好将选项用括号括起来。另外,表达式中的空格也会被匹配上。正确的模式是:(.*0.*0.*0.*)|(.*1.*1.*1.*)。建议使用 Regex101 来尝试正则表达式。

英文:

There is no such operator || in RegEx, only |, and it is good to wrap your options in parentheses. Also, the spaces in your expression are matched too. The right pattern is: (.*0.*0.*0.*)|(.*1.*1.*1.*).
P.S. I suggest using Regex101 for trying out regular expressions.

huangapple
  • 本文由 发表于 2020年7月23日 13:43:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/63047606.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定