Ehsan
Ehsan

Reputation: 45

how to search in a string includes \n by re.search

I am using python 3.8. I have an string as following:

s="V    n :=
v1  5 ;"

And I want to get the string between ":=" and ";" (which includes newline (\n)) . I run following command:

x = re.search(r'n :=(.*?);', s).group(1)

But I get following error:

AttributeError: 'NoneType' object has no attribute 'group'

which means it cannot find the string. While when I remove newline (\n) from input string:

s="V    n := v1 5 ;"

it works correctly without error! how can I solve the problem?

Upvotes: 1

Views: 136

Answers (2)

Kostas Drk
Kostas Drk

Reputation: 335

Try this:

search(r":=\s*(.*);", s).group(1)

Simply use \s to match newlines and whitespace. No need for additional flags.

Upvotes: 0

Bobby Ocean
Bobby Ocean

Reputation: 3328

You want the re.DOTALL flag to change "." to include "\n":

x = re.search(r'n :=(.*?);', s, flags=re.DOTALL).group(1)

Upvotes: 1

Related Questions