V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
RangerWolf
V2EX  ›  正则表达式

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

  •  
  •   RangerWolf · 2015-04-21 11:06:06 +08:00 · 2060 次点击
    这是一个创建于 3291 天前的主题,其中的信息可能已经有所发展或是发生改变。
    比如有 aa(bbb)ccc
    我只会一个 \(.*\)
    但是这样会把圆括号也带上, 即输出: (bbb)
    有没有能只取出圆括号里面的内容的正则? 不带圆括号...
    9 条回复    2015-04-21 18:08:56 +08:00
    rming
        1
    rming  
       2015-04-21 11:25:44 +08:00
    weyou
        2
    weyou  
       2015-04-21 11:26:40 +08:00
    用正则的group啊, \((.*)\)
    weyou
        3
    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
        4
    RangerWolf  
    OP
       2015-04-21 13:20:42 +08:00
    @weyou 感谢~ 如果是仅 .group() 不是 group(1)的话 还是会带圆括号
    zhyu
        5
    zhyu  
       2015-04-21 13:33:22 +08:00   ❤️ 1
    @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
        6
    wmttom  
       2015-04-21 14:15:06 +08:00   ❤️ 1
    >>> import re
    >>> re.search(r"(?<=\()\S+?(?=\))", "aa(bbb)ccc").group()
    200cc
        7
    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
        8
    RangerWolf  
    OP
       2015-04-21 18:08:19 +08:00
    @wmttom 赞!非常感谢!
    RangerWolf
        9
    RangerWolf  
    OP
       2015-04-21 18:08:56 +08:00
    @zhyu 是的~ 只不过之前那位兄弟的正则 还是没把圆括号去掉
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1086 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 22:37 · PVG 06:37 · LAX 15:37 · JFK 18:37
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.