rgshenoy
rgshenoy

Reputation: 449

RegEx for matching 7 digit numbers but not ones with a prefix

I'm trying to detect 7 digit numbers from plain text and this is the regular expression I'm using.

Regex sevenDigit = new Regex(@"(?<!\d)\d{7}(?!\d)");

Now, I want to be able to match only those 7 digit numbers, that do not begin with a particular prefix. Specifically "usr_id". How can I modify this regex to match only those that are not of the form usr_id=1234567 ?

Thanks!

Upvotes: 1

Views: 1516

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336238

I would do this:

Regex sevenDigit = new Regex(@"(?<!usr_id=)\b\d{7}\b");

Note also the \b word boundaries which are a more elegant way of saying "start of number" and "end of number". They don't match exactly like your (?<!\d) and (?!\d) lookaround assertions (most notably, they would not allow 1234567 to match within abc1234567xyz which your regex would allow to match). So if you really need this approach, you could also do

Regex sevenDigit = new Regex(@"(?<!\d|usr_id=)\d{7}(?!\d)");

Upvotes: 4

Related Questions