【问题标题】:Match the parentheses with or without a text in it - Regex匹配带有或不带有文本的括号 - 正则表达式
【发布时间】:2017-09-24 19:13:21
【问题描述】:

以下是我的文字-

Lorem Ipsum 来自“de Finibus”的第 1.10.32 和 1.10.33 节 Bonorum et Malorum”(善与恶的极端),西塞罗写的 公元前 45 年。这也应该匹配 () 和 ()。

我试图在其中匹配文本 -

  • (善恶之极)
  • ()
  • ( )

我的正则表达式 - \(.\) 不起作用。

我还尝试了\(*\),它与( ) 的()、) 和(The Extremes of Good and Evil) 的) 匹配。让我知道我在这里做错了什么。

【问题讨论】:

  • 你的文字会在括号内加括号吗?
  • (Foo(Bar)) 呢?
  • 试试这个\(.*\)
  • @IngoBürk (?:()(.*|).*)(?:\b))|(?:()((?!)).*?)?(?: ))

标签: javascript regex character-class


【解决方案1】:

您需要一个量词* 来匹配括号内的零个或多个字符。也使它变得懒惰?,所以只要它到达第一个右括号\(.*?\),它就会停止:

var s = 'Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This should also match () and ( ).'

console.log(
  s.match(/\(.*?\)/g)
)

【讨论】:

  • 感谢它的工作......你能告诉我为什么在这种情况下需要问号吗?
  • ? 是一个惰性量词,用于告诉匹配在第一个 ) 处停止,如果没有 ?,它将匹配到字符串中的最后一个 )。
【解决方案2】:

我的正则表达式 - \(.\) 不起作用。

这匹配一对括号,正好有一个之间的其他字符。

我还尝试了 \(*\),它匹配 ()、() 的 ) 和 (The Extremes of Good and Evil) 的 )。让我知道我在这里做错了什么。

在那里,您匹配任意数量的包括零个左括号(因为通配符适用于左括号),然后是右括号。

你想要这个:

\([^)]*\)

即:

  • 一个左括号,后跟
  • 除右括号外的零个或多个字符,后跟
  • 右括号。

您需要以某种方式从中间的字符中排除右括号,否则您将从第一个左括号到最后一个右括号的所有内容作为单个匹配项进行匹配。

【讨论】:

    【解决方案3】:

    这应该与您要查找的内容完全匹配。在每行的非全局级别上使用它进行解析时 - 它将解析括号。

    (?:\()  #Non-Capture Group Parenthesis - for advanced submatching regex.
    (       # Start Capture Group 1
     (?!\)) # Negative Lookahead
       .*?  # Match all characters except line break + Lazy
    )?      # End Capture Group 1 + Lazy (empty parenthesis)
    (?:\))  #Non-Capture Group Parenthesis - for advanced submatching regex.
    

    见下文...

    var s = 'Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This should also match () and ( ).'
    
    console.log(
      s.match(/(?:\()((?!\)).*?)?(?:\))/g)
    )
    
    //CONSOLE OUTPUT
    (3) ["(The Extremes of Good and Evil)", "()", "( )"]
    0: "(The Extremes of Good and Evil)"
    1: "()"
    2: "( )"
    length: 3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-03
      • 1970-01-01
      • 2014-01-25
      相关资源
      最近更新 更多