Skip to content Skip to sidebar Skip to footer

Python And Regex - Extracting A Number From A String

I'm new to regex, and I'm starting to sort of get the hang of things. I have a string that looks like this: This is a generated number #123 which is an integer. The text that I'

Solution 1:

You don't really need a fancy regex. Just use a group on what you want.

re.search(r'#(\d+)', 'This is a generated number #123 which is an integer.').group(1)

if you want to match a number in the middle of some known text, follow the same rule:

r'some text you know (\d+) other text you also know'

Solution 2:

res = re.search('#(\d+)', 'This is a generated number #123 which is an integer.')

if res is not None:
    integer = int(res.group(1))

Solution 3:

You can just use the findall() in the re module.

string="This is a string that contains #134534 and other things"
match=re.findall(r'#\d+ .+',string);
print match

Output would be '#1234534 and other things'

This will match any length number #123 or #123235345 then a space then the rest of the line till it hits a newline char.


Solution 4:

if you want to get the numbers only if the numbers are following text "This is a generated number #" AND followed by " which is an integer.", you don't have to do look-behind and lookahead. You can simply match the whole string, like:

"This is a generated number #(\d+) which is an integer."

I am not sure if I understood what you really want though. :)

updated

In [16]: a='This is a generated number #123 which is an integer.'                                                                        

In [17]: b='This should be a generated number #123 which could be an integer.'

In [18]: exp="This is a generated number #(\d+) which is an integer."

In [19]: result =re.search(exp, a)                                                                                                       

In [20]: int(result.group(1))
Out[20]: 123

In [21]: result = re.search(exp,b)

In [22]: result == None
Out[22]: True

Post a Comment for "Python And Regex - Extracting A Number From A String"