I am trying to check if my string contains some regular expression.
The strange thing is is, that while re.sub() would find the regex and will replace it, re.match() does not return any results...
Here is my usage:
re.match(): - trying to match the pattern ,\s*param2 - nothing is returned
>>> str = 'func(param1, param2)'
>>> str
'func(param1, param2)'
>>> results = re.match(r',\s*param2', str)
>>> print(results)
None
re.sub(): - Successfully replacing the same pattern ,\s*param2 by " hello"
>>> str = 'func(param1, param2)'
>>> str
'func(param1, param2)'
>>> new_str = re.sub(r',\s*param2', ' hello', str)
>>> new_str
'func(param1 hello)'
How can I match the pattern ,\s*param2 without substituting it?
Note that re.match matches from the beginning of the string. You are probably looking for re.search. See search vs. match for some details.
>>> str = 'func(param1, param2)'
>>> re.match(r',\s*param2', str)
>>> re.search(r',\s*param2', str)
<_sre.SRE_Match object at 0x7f16b72b83d8>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With