Justin
Justin

Reputation: 78

Need regex pattern for parsing out elements of string that are similar

For example, the string I'm trying to parse is:

#12 Alabama St. (AL) (12-14)

What would be the regex to select "Alabama St. (AL)"? I am able to get the (12-14) using:

\(([0-9]{1,2}-[0-9]{1,2})\)

Upvotes: 1

Views: 37

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626926

You may use

#\d+\s*(.*?)\s*\(\d{1,2}-\d{1,2}\)

See the regex demo.

Details

  • #\d+ - # and then 1+ digits
  • \s* - 0+ whitespaces
  • (.*?) - Group 1: any 0+ chars other than line break chars, as few as possible
  • \s* - 0+ whitespaces
  • \(\d{1,2}-\d{1,2}\) - (, 1 or 2 digits, -, 1 or 2 digits, ).

Python demo:

import re
text = "#12 Alabama St. (AL) (12-14)"
m = re.search(r'#\d+\s*(.*?)\s*\(\d{1,2}-\d{1,2}\)', text)
if m:
  print(m.group(1)) # => Alabama St. (AL)

Upvotes: 1

Related Questions