curP =“https://programmers.co.kr/learn/courses/4673'>#!Muzi#Muzi!]jayg07con&”
我想用正则表达式从这个字符串中找到Muzi
例如
MuziMuzi :计数0,因为它认为它是一个单词
Muzi&Muzi:数数2,因为它有,所以它把单词分开
7 Muzi7Muzi:伯爵2
我尝试使用regex来查找所有匹配的
curP = "<a href='https://programmers.co.kr/learn/courses/4673'></a>#!Muzi#Muzi!)jayg07con&&"
pattern = re.compile('[^a-zA-Z]muzi[^a-zA-Z]')
print(pattern.findall(curP))我期待着“!Muzi#”,“#Muzi!”但结果是
'!muzi#‘
发布于 2019-09-06 12:56:36
您需要使用这个作为正则表达式:
pattern = re.compile('[^a-zA-Z]muzi(?=[^a-zA-Z])', flags=re.IGNORECASE)(?=[^a-zA-Z])说,muzi必须具有[^a-zA-Z]的前瞻,但不消耗任何字符。因此,第一个匹配只匹配!Muzi,使下面的#可用来启动下一个匹配。
原来的regex正在消耗!Muzi#,它离开了Muzi!,这与正则表达式不匹配。
你们的比赛现在将是:
['!Muzi', '#Muzi']发布于 2019-09-06 13:30:33
据我所知,您希望获得关键字Muzi两边可能出现的任何值。
这意味着,在这种情况下,#必须由两个输出值共享。使用regex的唯一方法是在找到模式时操纵字符串。
这是我的解决方案:
import re
# Define the function to find the pattern
def find_pattern(curP):
pattern = re.compile('([^a-zA-Z]muzi[^a-zA-Z])', flags=re.IGNORECASE)
return pattern.findall(curP)[0]
curP = "<a href='https://programmers.co.kr/learn/courses/4673'></a>#!Muzi#Muzi!)jayg07con&&"
pattern_array = []
# Find the the first appearence of pattern on the string
pattern_array.append(find_pattern(curP))
# Remove the pattern found from the string
curP = curP.replace('Muzi','',1)
#Find the the second appearence of pattern on the string
pattern_array.append(find_pattern(curP))
print(pattern_array)输出:
['!Muzi#', '#Muzi!']https://stackoverflow.com/questions/57822233
复制相似问题