1

I need to find occurrences where there is a number followed by a hyphen and another number. eg. 5-10,6-12

ExampleString ="a5-10b,48-99z, 6-12, 5-9 ,4-2"
vals =  re.findall(r'(\s\d+\s?)-(\s?\d+\s?)' ,ExampleString)

I need the vals to capture 6-12, 5-9 ,4-2. I am finding it hard to capture only the numbers without the 48-99z. if I remove the question mark in the last \s? it does not capture 4-2 and if I keep it, it captures 48-99z(which I dont need)

Ritika
  • 79
  • 1
  • 8

2 Answers2

5

You could use the regex (\b\d+-\d+\b). The \b is a word boundary, like a comma, space, start/end of string, etc.

Here's an example: https://www.regexpal.com/?fam=111389

OdinX
  • 4,135
  • 1
  • 24
  • 33
1

You can apply

re.findall(r'(\d+-\d+)', ExampleString)

Only mention that information within the group that you want extract

Output

['5-10', '48-99', '6-12', '5-9', '4-2']
Arco Bast
  • 3,595
  • 2
  • 26
  • 53
Maninder
  • 31
  • 1