Search code examples
pythonpython-re

How to extract the number and only one string after the number using python?


I have a string with this pattern test_str = "Abc xyz another_name 123 V aaa". I need to extract the the number and the string after the number afterwards, as value and its unit. How can I do that?
I can only get the number using regex but can not the string after it which is the unit.

re.findall(r'[0-9]+', test_str)

the extected output is : 123 V

Edit:

Additioanly: some of the units may contains Slash or Back slash or numbers with comma, how can I get those as well ? Which means some of them could be 1.2 or 1,1 and for the units A/C orDC-W etc


Solution

  • This might be what you are looking for. This regex will return numbers followed by a space and a string.

    re.findall(r'[1-9]+ [a-zA-Z-\/]+', test_str)