Regular expression for inconsistent characters

If the language consists of the set {a, b, c} just how can we construct a regular expression for the language in which no two consecutive characters appear.

eg: abcbcabc will be valid and aabbcc will be rejected by regex.

0


a source to share


4 answers


This regex matches abcbcabc but not 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»

      


Edit



as explained in the comments, do line boundaries are important . Then the regex becomes

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

      

Kudos to Gumbo.

+4


a source


Can't we just keep it? Just "if not" is a regular expression:



/(aa|bb|cc)/

      

+2


a source


Assuming " ()

" is a grouping entry and " a|b

" means a

boolean or b

, then in pseudocode

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

      

Probably no need for grouping as Gumbo said . I have them there to be safe and clear.

+1


a source


You have to match the input to something like this (encoded anywhere) and if you find a match then this is the language you want:

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

      

+1


a source







All Articles