Reputation: 20856
I need to find the exact position where the string matched..
>>> pattern = 'Test.*1'
>>> str1='Testworld1'
>>> match = re.search(pattern,str1)
>>> match.group()
'Testworld1'
I need the position of 1(10th byte) from the 'Testworld1' string which matched the pattern .*1.
Upvotes: 1
Views: 101
Reputation: 30416
You want to do two things. First make a group out of the .*1
, then when accessing the group you can call .start()
Like so:
>>> pattern = 'Test.*(1)'
>>> match = re.search(pattern,str1)
>>> match.group(1)
'1'
>>> match.start(1)
9
Upvotes: 6
Reputation: 44259
How about end()
>>> pattern = r'Test.*1'
>>> str1='Testworld1'
>>> match = re.search(pattern,str1)
>>> match.end()
10
For more complicated applications (where you are not just looking for the last position of the last character in your match), you might want to use capturing and start
instead:
>>> pattern = r'Test.*(11)'
>>> str1='Testworld11'
>>> match = re.search(pattern,str1)
>>> match.start(1) + 1
10
Here, start(n)
gives you the beginning index of the capture of the n
th group, where groups are counted from left to right by their opening parentheses.
Upvotes: 3