apriltran95
apriltran95

Reputation: 31

How to find first letter in a string that doesn't repeat using regex (JS)?

Could you please help me in writing a pure regex expression to find the first letter that doesn't repeat in a string? I thought I might possibly need to use negative lookahead and negative lookbehind, but I don't think javascript supports lookbehind.

For e.g.

'NUNUMUNN'        // expected output 'M'
'LOMING'          // expected output 'L'

I think it's possible to do this using general string operations, but my preference is really for pure regex.

My starting point is currently this:

/(a-zA-Z).*?(?!\1)/.match('thestring');

But it doesn't work.

Upvotes: 3

Views: 183

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

Turn your logic around: First match all the letters in a word that do repeat, then match the next letter - that's the one you need to look at. Then there are some edge cases to consider.

/\b(?:(?:([a-z])(?=[a-z]*\1))+(?!\1))?([a-z])(?![a-z]*\2)/ig

Explanation:

\b          # Start of word
(?:         # Start of non-capturing group (optional, see below)
 (?:        # Start of non-capturing group that matches...
  ([a-z])   # ...and captures any ASCII letter
  (?=       # if it's followed by
   [a-z]*   #  zero or more letters 
   \1       #  and the same letter again.
  )         # (end of lookahead assertion)
 )+         # Repeat at least once
 (?!\1)     # Assert that this letter doesn't follow immediately to avoid matching "AAA"
)?          # Make that group optional (in case there are no repeated letters in the word)
([a-z])     # Then match a letter and capture it in group 2.
(?![a-z]\2) # and make sure that letter doesn't immediately repeat either.

Note that you will need to look at group 2 of a match in order to get the result - group 1 will contain whatever comes before the first non-repeating letter.

Test it live on regex101.com.

Upvotes: 3

Related Questions