lax123
lax123

Reputation: 21

Get a particular string after matching a string in regex python

I am new python programming. I have been trying to find some data after matching a string using regex.

For example:

str1 = 'ethernet33 20628103568 111111 22222222222 '

I am only looking for '20628103568', however with my code, it is printing everything after ethernet33

Here is the code

match1 = re.search("(?<=ethernet33\s).*(?<=\s)", str1)
print match1.group()

output:

20628103568 111111 22222222222

expected output:

20628103568 

Any guidance on how to modify the above regex to achieve this is would be much appreciated

Upvotes: 0

Views: 55

Answers (2)

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48077

You should be using this regex instead:

>>> import re

#          to match only the digits with  v
#    your "positive lookbehind assertion" v
>>> match1 = re.search('(?<=^ethernet33\s)\d+', str1)
#                           ^ to just match the pattern at the start of string.
#                           ^ prevents additional traversals
>>> match1.group()
'20628103568'

Upvotes: 2

tkhurana96
tkhurana96

Reputation: 939

In your case, I think str1.split()[1] might help

Upvotes: 0

Related Questions