I have a regular expression that I'm iterating over a large number of search terms that I don't control. Is there a way to detect special characters and treat them as part of the search rather than as regular expression terms?
Edit I clarified the question
searchTerms = ['ThisIsMySearchString(LSB)', 'OtherSearchTerm']
list = ['ThisIsMySearchString(LSB)OtherStuffInString', 'OtherStringsToSearch']
for item in searchTerms:
if (re.search(item, list, re.I)):
print('found item')
You can escape the (
in your regex to make it treat it not as a special character but rather one to match. so:
re.search('ThisIsMySearchString(LSB)', list, re.I)
becomes
re.search('ThisIsMySearchString\(LSB\)', list, re.I)
In general, you use \\
to escape the special character, like .
which becomes \\.
if you want to search on it.
Update
OK, now with new information, I would try to use Python's powerful batteries included features to find your terms. Something like:
searchTerms = ['ThisIsMySearchString(LSB)', 'OtherSearchTerm']
list = ['ThisIsMySearchString(LSB)OtherStuffInString', 'OtherStringsToSearch']
for term in searchTerms:
for item in list:
if term in item:
print(f'Found {term} in the list!')
which, for me, gives:
Found ThisIsMySearchString(LSB) in the list!
只需使用\\即可对括号进行转义。
if (re.search('ThisIsMySearchString\(LSB\)', list, re.I)):
Use re.escape
on your patterns first and then normally use re.search
. This assumes that you only have literal patterns and never want any special meaning in the patterns.
searchTerms = ['ThisIsMySearchString(LSB)', 'OtherSearchTerm']
list = ['ThisIsMySearchString(LSB)OtherStuffInString', 'OtherStringsToSearch']
for item in searchTerms:
for targetText in list:
if (re.search(re.escape(item), targetText, re.I)):
print('found item', item, 'in', targetText)
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.