Matching exactly one occurrence in a string with a regular expression

I know it's not right to answer your own question, but I basically merged your answers ... please don't flame :)

^(?=.{6}$) *C *$

Edit: Replacing . with Tomalak's response below [ C] increases the speed with about 4-5% or so

^(?=[ C]{6}$) *C *$


^(?=[ C]{6}$) *C(?! *C)

Explanation:

^             # start-of-string
(?=[ C]{6}$)  # followed by exactly 6 times " " or "C" and the end-of-string
 *C           # any number of spaces and a "C"
(?! *C)       # not followed by another C anywhere (negative lookahead)

Notes:

  • The ^(?=…{6}$) construct can be used anywhere you want to measure string length but not actually match anything yet.
  • Since the end of the string is already checked in the look-ahead, you do not need to put a $ at the end of the regex, but it does not hurt to do it.

Tags:

Regex