Python 使用正则表达式查找模式?
curP=”https://programmers.co.kr/learn/courses/4673“>#!Muzi#Muzi!)jayg07con&” 我想用regex从这个字符串中找到MuziPython 使用正则表达式查找模式?,python,regex,Python,Regex,curP=”https://programmers.co.kr/learn/courses/4673“>#!Muzi#Muzi!)jayg07con&” 我想用regex从这个字符串中找到Muzi 例如 MuziMuzi:计数0,因为它认为是一个单词 Muzi&Muzi:count 2,因为它有和,所以它将单词分开 7Muzi7Muzi:计数2 我尝试使用正则表达式查找所有匹配的 curP = "<a href='https://programmers.co.kr/learn/course
例如
MuziMuzi:计数0,因为它认为是一个单词
Muzi&Muzi:count 2,因为它有和,所以它将单词分开
7Muzi7Muzi:计数2
我尝试使用正则表达式查找所有匹配的
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))
curP=“#Muzi#Muzi!)jayg07con&”
pattern=re.compile(“[^a-zA-Z]muzi[^a-zA-Z]”)
打印(模式findall(curP))
我以为会是['!muzi#','#muzi!']
但结果是['!muzi#']
您需要将其用作正则表达式:
pattern = re.compile('[^a-zA-Z]muzi(?=[^a-zA-Z])', flags=re.IGNORECASE)
(?=[^a-zA-Z])
表示muzi
必须在[^a-zA-Z]
前面有一个字符,但不使用任何字符。所以第一个匹配只匹配!Muzi
留下下面的#
开始下一场比赛
您原来的正则表达式正在使用!穆齐#
离开Muzi代码>,与正则表达式不匹配
您的比赛现在将是:
['!Muzi', '#Muzi']
据我所知,您希望获得关键字Muzi两侧可能出现的任何值
这意味着在这种情况下,#
必须由两个输出值共享。
使用正则表达式的唯一方法是在找到模式时操作字符串
以下是我的解决方案:
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)
你怎么能因为没有指定flags=re而匹配任何东西呢?IGNORECASE
和muzi
因此将不匹配muzi
?你是否试图拆分出现在
之后和之前的术语
['!Muzi#', '#Muzi!']