0

How can I do a search with regex if I'm looking for a text block with line breaks?

Ej:

import re

t= '''  #ven=W_insert()
    #ven.play()
    xxxxxxxf
    zacku'''

x= '''  #ven=W_insert()
    #ven.play()
    xxxxxxxf
    zacku'''

print(re.search(x,t))

when I try to do it the result I get is 'none'.

I need to locate a block of text within a very large text. That is why x == t does not work for this case

How can I do it?

0

1 Answer 1

1

The reason that doesn't work has nothing to do with multiline strings. ( and ) are special characters in regex patterns, which are used to denote capture groups, that's why your search fails.

If you need to search for a pattern with literal ( or ) you can always escape them with backslashes \ (I also used a raw-string literal here, as is preferable with regex patterns):

import re

t = '''  #ven=W_insert()
    #ven.play()
    xxxxxxxf
    zacku'''

x = r'''  #ven=W_insert\(\)
    #ven.play\(\)
    xxxxxxxf
    zacku'''    

print(re.search(x, t))

Output:

<_sre.SRE_Match object; span=(0, 56), match='  #ven=W_insert()\n    #ven.play()\n    xxxxxxxf\>

You can also use re.escape to do the escaping automatically:

import re

t = '''  #ven=W_insert()
    #ven.play()
    xxxxxxxf
    zacku'''

x = '''  #ven=W_insert()
    #ven.play()
    xxxxxxxf
    zacku'''    

print(re.search(re.escape(x), t))

Output:

<_sre.SRE_Match object; span=(0, 56), match='  #ven=W_insert()\n    #ven.play()\n    xxxxxxxf\>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.