-4

Consider like I have a string:

stringA = "values-are-10-1,20-2,30-1,40-4,50-3"

I need to get only the strings : desired output:

for stringA: 10-1,20-2,30-1,40-4,50-3

How to build regex for this.

Dharman
  • 30,962
  • 25
  • 85
  • 135
wanderors
  • 2,030
  • 5
  • 21
  • 35
  • 2
    You want to cut off the string "values-are-" from the beginning? Is that the requirement? because you don't need a regular expression for that. – khelwood Mar 15 '22 at 10:04

2 Answers2

2

I suggest you use regex module:

import re
stringA = "values-are-10-1,20-2,30-1,40-4,50-3"
re.sub("[^0-9\-\,]", "", stringA).strip("-")

Output

10-1,20-2,30-1,40-4,50-3
TheFaultInOurStars
  • 3,464
  • 1
  • 8
  • 29
1

You can use this regex to do what you want :

(.[0-9]-[0-9])

Demo

With python code, you can do like this :

import re

regex = r"(.[0-9]-[0-9])"

stringA = "\"values-are-10-1,20-2,30-1,40-4,50-3\""

print([x.group() for x in re.finditer(regex, stringA, re.MULTILINE)])

Output :

['10-1', '20-2', '30-1', '40-4', '50-3']
  • 1
    `[0-9]+-[0-9]+` would make more sense, so you're not assuming the length of each number. I understand the OP's requirements are not very precise. – khelwood Mar 15 '22 at 10:08
  • 1
    Yes, we can use also your suggestion –  Mar 15 '22 at 10:21