Python 正则问题

2021-01-01 09:37:29 +08:00
 lemonnn
我想要匹配"[ )"或者 "( ]"中的内容,于是我写了这样一个正则:
str = '[123)(abc]'
m = re.findall('\[(.*?)\)|\((.*?)]',str)

我想要得到[’123‘ , ’abc‘]这样一个数组结果
但结果是[('123', ' '), (' ', 'abc')]
2057 次点击
所在节点    Python
8 条回复
ClericPy
2021-01-01 09:56:59 +08:00
import re

string = '[123)(abc]'

m = re.findall(r'[\[()](.*?)[)\]]', string)
print(m)
# ['123', 'abc']

这样吗?
ClericPy
2021-01-01 09:57:25 +08:00
上面发错, 被自动补全了括号

# -*- coding: utf-8 -*-

import re

string = '[123)(abc]'

m = re.findall(r'[\[(](.*?)[)\]]', string)
print(m)
ClericPy
2021-01-01 09:58:23 +08:00
睡晕了... 上面这俩回复都不对... 会有误判
crclz
2021-01-01 10:00:50 +08:00
('123', '') 表示 123 在第一个 group(括号)内被匹配。
('', 'abc') 表示 abc 在第二个 group(括号)内被匹配。
crclz
2021-01-01 10:03:32 +08:00
import re

def single(l):
assert len(l) == 1
return l[0]

s = '[123)(abc]'

# m = re.findall()
m = re.findall('\[(.*?)\)|\((.*?)]',s)
m = [single([q for q in p if len(q)>0]) for p in m]
print(m)
ClericPy
2021-01-01 10:16:30 +08:00
# -*- coding: utf-8 -*-

import re

string = '[123)(abc]'

m = re.findall(r'(?<=\[).*?(?=\))|(?<=\().*?(?=\])', string)
print(m)
# ['123', 'abc']
lemonnn
2021-01-01 10:27:31 +08:00
解决了,谢谢。 @ClericPy @crclz
learningman
2021-01-01 15:15:51 +08:00
@ClericPy 在这种回复不支持 markdown 的网站发代码,可以用 pastebin

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/740825

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX