Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string by using two substrings in Python

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?

like image 343
Sarp Kaya Avatar asked Nov 19 '13 03:11

Sarp Kaya


People also ask

How do you split a string into two substrings in Python?

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.

Can I split a string by two delimiters Python?

Python has a built-in method you can apply to string, called . split() , which allows you to split a string by a certain delimiter.

How do I split a string into substrings?

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.

How do you split a string into multiple words in Python?

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.


1 Answers

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 '
like image 179
Roger Pate Avatar answered Oct 29 '22 15:10

Roger Pate