简体   繁体   中英

regex ignore some characters when searching

I want to be able to match a substring in a string, but I want my search to be robust to some predefined characters inserted in the original string. To give an example:

string = "This is a text containing several sentences. This is a first test string\n\n. This test string should also be matched\t."
substring = "This is a first test string. This test string should also be matched."

I want to return the index of the substring in the original string (typically re.search(substring, string, re.IGNORECASE).spans() )

How can I ignore those meta characters (\n, \t) when searching?

Remove \n and \t from string before doing find . You don't need to perform re.search :

>>> re.sub(r'[\n\t]+', '', string).lower().find(substring.lower())
45

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM