晕了,求助一个正则如何写,要把圆括号里面的内容取出来

2015-04-21 11:06:06 +08:00
 RangerWolf
比如有 aa(bbb)ccc
我只会一个 \(.*\)
但是这样会把圆括号也带上, 即输出: (bbb)
有没有能只取出圆括号里面的内容的正则? 不带圆括号...
2069 次点击
所在节点    正则表达式
9 条回复
rming
2015-04-21 11:25:44 +08:00
weyou
2015-04-21 11:26:40 +08:00
用正则的group啊, \((.*)\)
weyou
2015-04-21 11:30:53 +08:00
>>> import re
>>> a = "this is a (test), isn't it"
>>> re.search(r'\((.*)\)', a).group(1)
'test'
RangerWolf
2015-04-21 13:20:42 +08:00
@weyou 感谢~ 如果是仅 .group() 不是 group(1)的话 还是会带圆括号
zhyu
2015-04-21 13:33:22 +08:00
@RangerWolf
re.MatchObject.group([group1, ...])

Returns one or more subgroups of the match. If there is a single argument, the result is a single string; if there are multiple arguments, the result is a tuple with one item per argument. Without arguments, group1 defaults to zero (the whole match is returned).

.group()和.group(0)一样,返回的是全部的匹配内容
wmttom
2015-04-21 14:15:06 +08:00
>>> import re
>>> re.search(r"(?<=\()\S+?(?=\))", "aa(bbb)ccc").group()
200cc
2015-04-21 15:31:04 +08:00
var s = 'aa(bbb)ccc';
var r = /\((.*)\)/g;
var result = r.exec(s)[1]; // bbb
RangerWolf
2015-04-21 18:08:19 +08:00
@wmttom 赞!非常感谢!
RangerWolf
2015-04-21 18:08:56 +08:00
@zhyu 是的~ 只不过之前那位兄弟的正则 还是没把圆括号去掉

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

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

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

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

© 2021 V2EX