Search code examples
regexregex-lookaroundsregex-negation

Negative Lookahead Regex is ignoring my sentence


I'm trying to get N group in the following text using this Regex N+(?!\d+N)

20NNN (Expected Result: NN)
2NNN  (Expected Result: NN)
2000NNNN (Expected Result: NNN)

When I execute the code, the Regex fails.

PS: The N group after number+N could be any quantity.

Thanks in advance


Solution

  • The N+(?!\d+N) pattern matches an N char, one or more occurrences, that is not immediately followed with 1+ digits and N.

    You may use

    (?<=\dN)N+
    

    See the regex demo

    Details

    • (?<=\dN) - a location immediately preceded with any digit and N
    • N+ - one or more N chars.