非连续字符的正则表达式

时间:2009-05-15 06:17:37

标签: regex

如果某种语言包含{ a b c },那么我们怎样才能为其中的语言构建正则表达式没有两个连续的字符出现。

例如: abcbcabc 将有效, aabbcc 将被正则表达式拒绝。

4 个答案:

答案 0 :(得分:4)

这个正则表达式匹配 abcbcabc 但不匹配 aabbcc

// (?:(\w)(?!\1))+
// 
// Match the regular expression below «(?:(\w)(?!\1))+»
//    Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
//    Match the regular expression below and capture its match into backreference number 1 «(\w)»
//       Match a single character that is a “word character” (letters, digits, etc.) «\w»
//    Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?!\1)»
//       Match the same text as most recently matched by capturing group number 1 «\1»

修改

正如评论中所解释的那样,字符串边界很重要。然后正则表达式成为

\m(?:(\w)(?!\1))+\M

向Gumbo致敬。

答案 1 :(得分:2)

我们不能保持简单吗?只是'如果不是'这个正则表达式:

/(aa|bb|cc)/

答案 2 :(得分:1)

假设“()”是分组符号,“a|b”代表a 逻辑 - 或 b,那么,伪代码

if regexp('/(aa)|(bb)|(cc)/', string) == MATCH_FOUND
  fail;
else
  succeed;

正如Gumbo所说,可能不需要分组。我把它们放在那里是为了安全和清晰。

答案 3 :(得分:1)

你必须将输入与这样的东西相匹配(以你想要的任何方式编码),如果你发现巧合,那么它就是你想要的语言:

[^{aa}|{bb}|{cc}]