0

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

2 Answers 2

2

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'
Sign up to request clarification or add additional context in comments.

4 Comments

Beat me to it :). FWIW, just str1.split()[1] would do in this case.
Additionally, matching the start with ^ would save you further traversal: (?<=^ethernet33\s)\d+
@heemayl : correct, thanks! it is more efficient. Added it to the answer too
Awesome!!.. Thanks for help
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.