Asaf
Asaf

Reputation: 75

conditional regex - Javascript

I want to remove number containing between 6 and 8 digits, so the regex I am using is: \b\d{6,8}

It works fine, but, it if I have two numbers separated by an underscore (_), for example 1234567890_12345678901234567890 I want it removed as well. I must use \b (boundary).

To me it seems like a condition:

match numbers between 6 and 8 digit, but if you see two numbers separated by an underscore match them too (regardless of the number of digits in each number).

match: 12345678

match: 12345678934567_1234567890123456789

match: 123_23

no match: 12345

I need a single regex that handles both cases.

Thanks a lot.

Upvotes: 1

Views: 971

Answers (3)

Adam
Adam

Reputation: 5233

You can try this one as well:

\b\d+(?:\d{4,6}|_)\d+\b

And if you'd like to allow more than one _ characters, try this one:

\b\d+(?:\d{4,6}|_[\d_]*)\d+\b

This second one will match on this too: 12345678934567_1234567890_123456789

Upvotes: 0

Alex Kopachov
Alex Kopachov

Reputation: 733

You may use this

^(\d+_\d+)|(\d{6,8})$

This regex contains two parts:

  1. (\d+_\d+) covers cases with "_" symbol;

  2. (\d{6,8}) covers other cases

Upvotes: 1

Neil
Neil

Reputation: 5780

Try the following:

\b(?:\d{6,8}|\d+_\d+)\b

It is simply 6 to 8 digits or any number_number.

Click here to see it in action.

Upvotes: 3

Related Questions