0

If I need to find a regex that matches any positive number of lower case characters, an N, and then either 6 integers, 8 integers or 15 integers. But not match any other number of intagers

e.g. "abcN123456" or "abcdN12345678" or "abN123456789012345" or "abcdefgN123456"

How would you make a regex that finds this?

It starts with [a-z]+N but don't know how to do the variable number of integers

2 Answers 2

5

This is how I would do it:

[a-z]+N(\d{6}|\d{8}|\d{15})    
3
  • This regex returns a match for 7 integers (as it finds 6 then ignores the last int) is there a way around this?
    – puser
    Nov 5, 2013 at 13:15
  • 1
    you could add characters that follow the string (e.g. comma, whitespaces (\s) or quotes) or if the string end after that use $ to end the regex like so: [a-z]+N(\d{6}|\d{8}|\d{15})$
    – grexter89
    Nov 5, 2013 at 13:17
  • 1
    Or \b to match the end of a word.
    – MikeFHay
    Nov 5, 2013 at 13:24
2

Here's a possible solution

^[a-z]+N(?:\d{6}|\d{8}|\d{15})$

Regular expression visualization

Debuggex Demo

or try this "crazier" variant ;)

^[a-z]+N(?:\d{6}|(?:(?:\d{7}){1,2}\d))$

Regular expression visualization

Debuggex Demo

2
  • This regex returns a match for 7 integers (as it finds 6 then ignores the last int) is there a way around this?
    – puser
    Nov 5, 2013 at 13:16
  • 1
    "fixed" it by adding selectors for start & end
    – bukart
    Nov 5, 2013 at 13:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.