Amp
Amp

Reputation: 111

Python matching dashes using Regular Expressions

I am currently new to Regular Expressions and would appreciate if someone can guide me through this.

import re
some = "I cannot take this B01234-56-K-9870 to the house of cards"

I have the above string and trying to extract the string with dashes (B01234-56-K-9870) using python regular expression. I have following code so far:

regex = r'\w+-\w+-\w+-\w+'
match = re.search(regex, some)
print(match.group()) #returns B01234-56-K-9870

Is there any simpler way to extract the dash pattern using regular expression? For now, I do not care about the order or anything. I just wanted it to extract string with dashes.

Upvotes: 0

Views: 1958

Answers (1)

vrintle
vrintle

Reputation: 5586

Try the following regex (as shortened by The fourth bird),

\w+-\S+

Original regex: (?=\w+-)\S+


Explanation:

  • \w+- matches 1 or more words followed by a -
  • \S+ matches non-space characters

Regex demo!

Upvotes: 1

Related Questions