2

how to match a number followed immediately by either /tcp or /udp or nothing?

the following illustrates 3 scenarios: input --> result

  1. 123/tcp_haha --> 123
  2. 123 --> 123
  3. 123abc/tcp --> no match

i used re.compile(r'(\d+)(?:\/[tcpud]{3})*')but it also matched in case 3.

EDIT: Guess it's really a follow up question: how to match digits either followed by /tcp or /udp or proceeded by tcp/ or /udp or just by itself? so

 1.    something else 123/tcp_haha --> 123
 2.    123  --> 123
 3.    123abc/tcp --> no match
 4.    udp/123 something else --> 123
 5.    tcp/123/tcp --> 123

3 Answers 3

4

Character class will match any combinations of its included characters. You need to use a logical OR instead.

r'^\d+(?:/tcp|/udp)?$'

?: is a non-capture group notation and ? will make your non-capture group optional (for non-suffix cases).

If you want to capture the string if something followed the /tcp you can use following regex:

r'^\d+(?:/tcp.*|/udp)?$'

Demo: https://regex101.com/r/oUm0e9/1

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

4 Comments

thanks for the reply! i just updated the post, realizing that i also want to capture the number even if something follows /tcp. how to achieve that? thanks again
hi @kas thanks for the reply again. I added a follow up question would be great if you could have a look. if it's too involved, i'll move it to a separate question.
@dragon_cat Just add the same thing to the leading. r'^(?:tcp/|udp/)?\d+(?:/tcp.*|/udp)?$'
yes, i have re.compile(r'(?:.*tcp/|.*udp/)?(\d+)(?:/tcp.*|/udp.*)?$'), but this requires both left and right to be either /tcp /udp or none. it will not match say apple123/tcp, which i would like to match.
1

How about this for your original problem:

^\d+(?=/tcp|/udp|$)

Comments

0

Use this regex after your edit:

\d+(?=\/tcp|\/udp)
  • \d+ matches one or more digit
  • (?=...) is a lookahead, match will stop if next characters are ...
  • \/tcp|\/udp matches a slash followed by tcp or udp

1 Comment

thanks for the reply! it works except fails to match all numbers (case 2)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.