Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Regex: "re.match()" works differently than "re.sub()" for regex [duplicate]

Tags:

python

regex

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?

like image 782
SomethingSomething Avatar asked Oct 27 '25 00:10

SomethingSomething


1 Answers

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>
like image 156
tobias_k Avatar answered Oct 29 '25 15:10

tobias_k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!