【问题标题】:Regex for matching data between parenthesis BUT with a pattern to match inside正则表达式用于匹配括号之间的数据,但带有要匹配的模式
【发布时间】:2020-10-15 21:47:39
【问题描述】:

我看到了很多例子,说明如何使用 python 的正则表达式获取括号之间的数据,但没有一个包含某种模式的例子。

例如,我有这样的数据:

Overall (each): 37 1/4 × 74 1/2 × 7 7/8 in. (94.6 × 189.2 × 20 dm)
Each, 30 x 50 in. (76.2 x 127 dm.)
24 3/8 x 14 5/8 x 5 1/8 in. (61.9 x 37.1 x 13 dm)

我至少要达到的目标是:

(94.6 × 189.2 × 20 dm)
(76.2 x 127 dm.)
(61.9 x 37.1 x 13 dm)

完美的结果将如下所示,但我确信这将需要第二次拆分:

94.6, 189.2, 20 
76.2, 127
61.9, 37.1, 13

目前,我正在尝试此代码:regex,但正如您所见,仅捕获 cm 括号数据没有成功。

【问题讨论】:

    标签: python regex pattern-matching parentheses


    【解决方案1】:

    使用

    \(([^()]*\bcm\b[^()]*)\)
    

    proof

    说明

    --------------------------------------------------------------------------------
      \(                       '('
    --------------------------------------------------------------------------------
      (                        group and capture to \1:
    --------------------------------------------------------------------------------
        [^()]*                   any character except: '(', ')' (0 or
                                 more times (matching the most amount
                                 possible))
    --------------------------------------------------------------------------------
        \b                       the boundary between a word char (\w)
                                 and something that is not a word char
    --------------------------------------------------------------------------------
        cm                       'cm'
    --------------------------------------------------------------------------------
        \b                       the boundary between a word char (\w)
                                 and something that is not a word char
    --------------------------------------------------------------------------------
        [^()]*                   any character except: '(', ')' (0 or
                                 more times (matching the most amount
                                 possible))
    --------------------------------------------------------------------------------
      )                        end of \1
    --------------------------------------------------------------------------------
      \)                       ')'
    

    【讨论】:

    • 你能推荐任何书来更好地解释上面的代码吗?
    • @Mensch regular-expressions.info 是一个了不起的资源。
    猜你喜欢
    • 2017-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-06
    • 1970-01-01
    相关资源
    最近更新 更多