用正则表达式找到模式?

2024-06-28 10:17:07 发布

您现在位置:Python中文网/ 问答频道 /正文

curP = "https://programmers.co.kr/learn/courses/4673'>#!Muzi#Muzi!)jayg07con&&"

我想用regex从这个字符串中找到Muzi
例如

MuziMuzi:计数0,因为它认为是一个单词
Muzi&Muzi:数到2,因为它有&;between,所以它将单词分开
7Muzi7Muzi:计数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#']


Tags: https单词learnregexpattern计数cokr
2条回答

据我所知,您希望获得关键字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!']

您需要将其用作正则表达式:

pattern = re.compile('[^a-zA-Z]muzi(?=[^a-zA-Z])', flags=re.IGNORECASE)

(?=[^a-zA-Z])表示muzi必须具有[^a-zA-Z]looaward,但不使用任何字符。所以第一个匹配只匹配!Muzi,剩下的#可以开始下一个匹配。你知道吗

您原来的正则表达式正在消耗!Muzi#而离开Muzi!,这与正则表达式不匹配。你知道吗

您的匹配项现在将是:

['!Muzi', '#Muzi']

相关问题 更多 >