[英]Regular expression search string with parentheses as part of string to detect in python
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. 好的,现在有了新信息,我将尝试使用Python强大的电池内置功能来查找您的条款。 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
. re.escape
在模式上使用re.escape
,然后通常使用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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.