Regular Expression Matching First Non-Repeated Character

Well let’s take your tooth example – here is what the regex-engine does (a lot simplified for better understanding)

Start with t then look ahead in the string – and fail the lookahead, as there is another t.

tooth
^  °

Next take o, look ahead in the string – and fail, as there is another o.

tooth
 ^°

Next take the second o, look ahead in the string – no other o present – match it, return it, work done.

tooth
  ^

So your regex doesn’t match the first unrepeated character, but the first one, that has no further repetitions towards the end of the string.

Leave a Comment