使用 re.findall()
,我正在尝试从字符串中的术语列表中找到每个术语的所有出现。
如果特定术语包含特殊字符(即a '+'
),则将找不到匹配,或者可以生成错误消息。使用re.escape()
,可以避免错误消息,但是在字符串中找不到具有特殊字符的术语。
import re
my_list = ['java', 'c++', 'c#', '.net']
my_string = ' python javascript c++ c++ c# .net java .net'
matches = []
for term in my_list:
if any(x in term for x in ['+', '#', '.']):
term = re.escape(term)
print "nlooking for term '%s'" % term
match = re.findall("\b" + term + "\b", my_string, flags = re.IGNORECASE)
matches.append(match)
上面的代码只会在字符串中找到" Java"。关于如何在字符串中找到特殊字符的术语的任何建议?
警告:我无法手动更改'my_list',因为我不知道它将包含什么术语。
update - 似乎问题与正则界线(" b")中的单词边界指示符有关字符串。目前尚不清楚如何以干净直接的方式解决此问题。
edit - 这个问题不是此问题的重复 - 它已经包含了该帖子中最适用的解决方案。
import re
my_list = ['java', 'c++', 'c#', '.net']
my_string = ' python javascript c++ c++ c# .net java .net'
matches = []
for term in my_list:
if any(x in term for x in ['+', '#', '.']):
term = re.escape(term)
print "nlooking for term '%s'" % term
match = re.findall(r"(?:^|(?<=s))"+term+r"(?=s|$)", my_string, flags = re.IGNORECASE)
matches.append(match)
尝试一下。问题是 b
,它是单词边界。在 C++
+
之后没有单词边界。