Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex expression for "string x/0/y"

Tags:

regex

Hallo everyone,

I am trying to find a resolution for a regex expression:

I want to have something like this

"string x/0/y" where x is in a range between 1-6 and y is in range between 1-48

I tried this:

interface GigabitEthernet [1-6]/0/([1-4]*[1-8])

but then if y = 50 it still takes 5 under consideration and drops "0"

I tried this

interface GigabitEthernet [1-6]/0/([1-4][1-8])

but then if y = 1-9 it does not match the expression.

I would appreciate any help on this.

Thank you !

like image 258
Paul Avatar asked Aug 12 '26 05:08

Paul


2 Answers

Try ([1-9]|[1-3][0-9]|4[0-8]) for the second part of your regex.

Keep in mind that if you need to do lots of similar searches, regex alone isn't necessarily the best tool for the job. Your program could instead search for the general pattern of /(\d+)/0/(\d+)/, extract the match groups, then validate the numeric ranges.

like image 61
Jacob Avatar answered Aug 14 '26 16:08

Jacob


I don't recommend trying to do numeric range checking within a regular expression. It's hard to write and even harder to read. Instead, use a regular expression like this:

(\d)/0/(\d{1,2})

Then, using the captured groups, check to make sure that the first one is

x >= 1 and x <= 6

and the second one is

y >= 1 and y <= 48

This will be much easier to read later, when you need to come back to it.


A concrete example in Python might be:

s = "5/0/14"
m = re.match(r"(\d)/0/(\d{1,2})", s)
if m is not None:
    x = int(m.group(1))
    y = int(m.group(2))
    if x >= 1 and x <= 6 and y >= 1 and y >= 48 then
        print("Looks good!")
like image 45
Greg Hewgill Avatar answered Aug 14 '26 16:08

Greg Hewgill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!