首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用regex找到模式?

使用regex找到模式?
EN

Stack Overflow用户
提问于 2019-09-06 12:40:21
回答 2查看 63关注 0票数 0

curP =“https://programmers.co.kr/learn/courses/4673'>#!Muzi#Muzi!]jayg07con&”

我想用正则表达式从这个字符串中找到Muzi

例如

MuziMuzi :计数0,因为它认为它是一个单词

Muzi&Muzi:数数2,因为它有,所以它把单词分开

7 Muzi7Muzi:伯爵2

我尝试使用regex来查找所有匹配的

代码语言:javascript
复制
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#‘

EN

回答 2

Stack Overflow用户

发布于 2019-09-06 12:56:36

您需要使用这个作为正则表达式:

代码语言:javascript
复制
pattern = re.compile('[^a-zA-Z]muzi(?=[^a-zA-Z])', flags=re.IGNORECASE)

(?=[^a-zA-Z])说,muzi必须具有[^a-zA-Z]的前瞻,但不消耗任何字符。因此,第一个匹配只匹配!Muzi,使下面的#可用来启动下一个匹配。

原来的regex正在消耗!Muzi#,它离开了Muzi!,这与正则表达式不匹配。

你们的比赛现在将是:

代码语言:javascript
复制
['!Muzi', '#Muzi']
票数 0
EN

Stack Overflow用户

发布于 2019-09-06 13:30:33

据我所知,您希望获得关键字Muzi两边可能出现的任何值。

这意味着,在这种情况下,#必须由两个输出值共享。使用regex的唯一方法是在找到模式时操纵字符串。

这是我的解决方案:

代码语言:javascript
复制
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)

输出:

代码语言:javascript
复制
['!Muzi#', '#Muzi!']
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57822233

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档