Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

python正则匹配问题

我想要匹配"[ )"或者 "( ]"中的内容,于是我写了这样一个正则:
`str = '[123)(abc]'
m = re.findall('[(.?))|((.?)]',str)`

我想要得到[’123‘ , ’abc‘]这样一个数组结果
但结果是[('123', ' '), (' ', 'abc')]
我应该如何修改?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

像这种需要匹配前后有特定字符的内容,用 零宽断言 比较合适。

  • 给出的代码使用的是子模式匹配
  • findall 多个子捕获成功,会以元组组成的列表呈现结果

正解如下

str = '[123)(abc]'
parttern = '(?<=[).*(?=))|(?<=().*(?=])'  # 分别使用正后发与正先行断言
m = re.findall(parttern, str)

print(m)  # ['123', 'abc']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...