I am searching a string by using re
, which works quite right for almost all cases except when there is a newline character(\n)
For instance if string is defined as:
testStr = " Test to see\n\nThis one print\n "
Then searching like this re.search('Test(.*)print', testStr)
does not return anything.
What is the problem here? How can I fix it?
Python String | split() split() method in Python split a string into a list of strings after breaking the given string by the specified separator. Parameters : separator : This is a delimiter. The string splits at this specified separator.
Python has a built-in method you can apply to string, called . split() , which allows you to split a string by a certain delimiter.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
split() by default will operate on all whitespace characters, grouping them together for the split. The result will be the list of words that you want.
The re module has re.DOTALL to indicate "." should also match newlines. Normally "." matches anything except a newline.
re.search('Test(.*)print', testStr, re.DOTALL)
Alternatively:
re.search('Test((?:.|\n)*)print', testStr)
# (?:…) is a non-matching group to apply *
Example:
>>> testStr = " Test to see\n\nThis one print\n "
>>> m = re.search('Test(.*)print', testStr, re.DOTALL)
>>> print m
<_sre.SRE_Match object at 0x1706300>
>>> m.group(1)
' to see\n\nThis one '
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