Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude certain numbers from range of numbers using Regular expression

Could some one help me with the regular expression, where we can exclude certain numbers in between from a range of numbers.

Presently, ^([1-9][0][0-9])$ is the regular expression that is configured. Now if i want to exclude a few numbers/one number(501,504) from it, then how would the regular expression look/be.

like image 223
Harish Shankar Avatar asked Feb 24 '16 03:02

Harish Shankar


People also ask

How do you exclude a regular expression?

To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself.

How do you specify a number range in regex?

Example: Regex Number Range 1-20 Range 1-20 has both single digit numbers (1-9) and two digit numbers (10-20). For double digit numbers we have to split the group in two 10-19 (or in regex: "1[0-9]") and 20. Then we can join all these with an alternation operator to get "([1-9]|1[0-9]|20)".

What does \+ mean in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

What can be matched using (*) in a regular expression?

You can repeat expressions with an asterisk or plus sign. A regular expression followed by an asterisk ( * ) matches zero or more occurrences of the regular expression. If there is any choice, the first matching string in a line is used.


1 Answers

Described in more detail in this answer, you can use the following regex with the “Negative Lookahead” command ?!:

^((?!501|504)[0-9]*)$

You can see the regex being executed & explained here: https://regex101.com/r/mL0eG4/1

  • /^((?!501|504)[0-9]*)$/mg
    • ^ assert position at start of a line
    • 1st Capturing group ((?!501|504)[0-9]*)
      • (?!501|504) Negative Lookahead - Assert that it is impossible to match the regex below
        • 1st Alternative: 501
          • 501 matches the characters 501 literally
        • 2nd Alternative: 504
          • 504 matches the characters 504 literally
      • [0-9]* match a single character present in the list below
        • Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
        • 0-9 a single character in the range between 0 and 9
    • $ assert position at end of a line
    • m modifier: multi-line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)
    • g modifier: global. All matches (don't return on first match)
  • like image 190
    Hugo Ferreira Avatar answered Nov 16 '22 00:11

    Hugo Ferreira