【问题标题】:Regex Capturing: repeating two letters正则表达式捕获:重复两个字母
【发布时间】:2014-09-10 11:56:48
【问题描述】:

我正在尝试检查一个单词是否有三个或更多重复的“两个字母减少”,但只有当 相同的字母被重复时,表达式才会返回 true。为什么?

(([a-z])([^\1]))\1\2{2,} 
    ^      ^     ^ ^  ^
    1      2     3 4  5

1) 任意字母(捕获集\1)
2) 任何未设置为 1 的字符(捕获设置 \2)
3) 再次捕获 \1
4) 再次捕获 \2
5) 至少两次

应该返回 TRUE 的单词: asasasassafasf, ereeeererererere, dddddtrtrtrtrtruuuuuuuu

应该返回 FALSE 的词: dddddddd, rrrrrrrrrrlkajf, fffffffssssssytytffffff

【问题讨论】:

  • 反向引用在字符类中不起作用(毕竟它们可能由多个符号组成)。请参阅 General approach for (equivalent of) "backreferences within character class"? 以了解前瞻替代方案。
  • 很少有例子将极大地帮助您澄清问题。
  • @anubhava asasasas bhbhbhbhbh blaytytytyt...
  • 你真的需要给我们举个例子。对have three or more repeating 'two letters pairs'有几种解释

标签: php regex


【解决方案1】:

您可以使用negative lookahead assertion 解决此问题:

([a-z])((?!\1)[a-z])(?:\1\2){2,}

测试它live on regex101.com

说明:

([a-z])  # Match and capture a single ASCII letter in group 1
(        # Match and capture...
 (?!\1)  # unless it's the same letter as the one captured before
 [a-z]   # a single ASCII letter in group 2
)        # End of group 2
(?:\1\2) # Match those two letters
{2,}     # two or more times

【讨论】:

  • 正如您在我的回答中的评论中指出的那样,这两个字母必须不同,+1 用于实现。 :)
【解决方案2】:

根据您的简短描述,以下正则表达式应该适合您:

(([a-z])((?!\2)[a-z]))\1{2}

Regex Demo

  • ([a-z]) - 匹配字母 a 到 z 并将它们捕获在一个组中
  • \2 - 对第 2 组的反向引用
  • (?!\2)[a-z]) - 匹配不是组 #2 的字母 a 到 z
  • \1{2} 2 个反向引用实例 #1

或使用相对反向引用编号

(([a-z])(?!\g{-1})[a-z])\1{2}

简而言之,此正则表达式匹配连续出现 3 次不同字符的字母对。

【讨论】:

  • 但也会返回一个重复的字母,例如:dddddddddddddd
  • 谢谢!但是为什么负前瞻 \2 而不是 \1?
  • 先开始的是数字1。所以外部(..) 是数字1,内部([a-z]) 是数字2
  • 明白了。谢谢!
  • 我还更新了答案以显示使用相对反向参考编号。
猜你喜欢
  • 1970-01-01
  • 2011-12-14
  • 1970-01-01
  • 2018-04-09
  • 1970-01-01
  • 1970-01-01
  • 2017-09-13
  • 2011-03-11
  • 2017-01-07
相关资源
最近更新 更多