-1

I am trying to do a regex match of port name(Ex: eth1/2/3)

re.match('[eE][tT][hH](\d+)/(\d+)/(\d)', value)

Its catching eth1/2a/1 as error , but not eth1/2/1a.

Can you please help.

1
  • Problem with my regex - not saying the end of string .Thanks Everyone for pointing out the mistake. Commented Mar 28, 2016 at 1:16

2 Answers 2

2

Try ^[eE][tT][hH]\d+(?:\/\d+){2}$ instead. Demo here

re.match will search for matches at the start of the input string. Since eth1/2/1a matched your pattern at the start (up to the letter a) it would still return a match. To stop that you need to put boundaries at the end of the regex, such as $ to make sure that you've consumed all the input string before a match is determined.

Sign up to request clarification or add additional context in comments.

1 Comment

With re.match, you do not need ^. Also, / does not have to be escaped.
1

It's happened because in first case 2a part doesn't match your regular expression. And in second case th1/2/1 perfectly match [eE][tT][hH](\d+)/(\d+)/(\d) and additional a symbol does not matter.

If you need to get something without any additional symbols try to add to your pattern $ to match end of string.

re.match('[eE][tT][hH](\d+)/(\d+)/(\d)$', value)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.