Python passive Regex and Lookbehind groups

I have a line:

# print thestring
abcd\t$500\n

      

I want to extract an unsigned 500 dollar value.

Here is my code:

# trying positive lookbehind
m = re.search('(<=\$)\d+$',thestring)
# trying passive groups
m = re.search('(?:\$)\d+$',thestring)

      

What am I doing wrong here?

+3


source to share


2 answers


Missing groups don't remove the result from the matched substring, which is why the second solution doesn't work. The first solution should work, but you don't seem to understand the syntax for positive lookbehind. It should be:



(?<=\$)\d+$

      

+5


source


First of all, you should either escape the backslash or use raw strings:

'(<=\\$)\\d+$'

      

or

r'(<=\$)\d+$'

      



Then why use lookbehind or passive group? You want to grab the number, right? What about:

m = re.search('\\$(\\d+)',thestring)

      

Then retrieve your number using m.group(1)

.

+3


source







All Articles