Home > Mobile >  Python - How to get only the numbers from a string which has got commas and hyphens in between
Python - How to get only the numbers from a string which has got commas and hyphens in between

Time:03-15

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

Could you please help me in getting regex for this.

CodePudding user response:

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']

CodePudding user response:

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
  • Related