tags:

views:

36

answers:

3

Hi,

I need to create a regexp to match strings like this 999-123-222-...-22 The string can be finished by &Ns=(any number) or without this... So valid strings for me are

999-123-222-...-22
999-123-222-...-22&Ns=12
999-123-222-...-22&Ns=12

And following are not valid:

999-123-222-...-22&N=1

I have tried testing it several hours already... But did not manage to solve, really need some help

A: 

If you just want to allow strings 999-123-222-...-22 and 999-123-222-...-22&Ns=12 you better use a string function.

If you want to allow any numbers between - you can use the regex:

^(\d+-){3}[.]{3}-\d+(&Ns=\d+)?$

If the numbers must be of only 3 digits and the last number of only 2 digits you can use:

^(\d{3}-){3}[.]{3}-\d{2}(&Ns=\d{2})?$
codaddict
+1  A: 

Not sure if you want to literally match 999-123-22-...-22 or if that can be any sequence of numbers/dashes. Here are two different regexes:

/^[\d-]+(&Ns=\d+)?$/

/^999-123-222-\.\.\.-22(&Ns=\d+)?$/

The key idea is the (&Ns=\d+)?$ part, which matches an optional &Ns=<digits>, and is anchored to the end of the string with $.

John Kugelman
A: 

This looks like a phone number and extension information.. Why not make things simpler for yourself (and anyone who has to read this later) and split the input rather than use a complicated regex?

s = '999-123-222-...-22&Ns=12'
parts = s.split('&Ns=') # splits on Ns and removes it

If the piece before the "&" is a phone number, you could do another split and get the area code etc into separate fields, like so:

phone_parts = parts[0].split('-') # breaks up the digit string and removes the '-'
area_code = phone_parts[0]

The portion found after the the optional '&Ns=' can be checked to see if it is numeric with the string method isdigit, which will return true if all characters in the string are digits and there is at least one character, false otherwise.

if len(parts) > 1:
    extra_digits_ok = parts[1].isdigit()
Martin Thomas