【问题标题】:Regex match between parenthesis stopping at first space within parenthesis括号之间的正则表达式匹配在括号内的第一个空格处停止
【发布时间】:2019-05-17 15:04:01
【问题描述】:

我有一个类似some data (920 seconds) 的字符串,并且只想提取920

到目前为止,我有 \([^)]*\) 来提取括号之间的所有文本。它返回(920 seconds)

( 在第一个空格处停止后,如何排除括号并提取任何内容?

编辑:920 是一个字符串,而不是一个整数,因为数据是如何格式化的

【问题讨论】:

  • 使用:\(([^\s)]*)[^)]*\) 并从捕获组 #1 中获取文本

标签: regex


【解决方案1】:

您可以使用捕获组来获取您的子字符串:

\(([^\s)]*)[^)]*\)

RegEx Demo

【讨论】:

    【解决方案2】:

    这里,我们可以简单地使用 ( 作为左边界,收集想要的数字:

    (.*?\()[0-9]+(.*)
    

    我们可以在数字周围添加一个捕获组并将其存储在$2

    (.*?\()([0-9]+)(.*)
    

    正则表达式

    如果不需要此表达式,可以在 regex101.com 中修改或更改它。

    正则表达式电路

    jex.im 可视化正则表达式:

    JavaScript 演示

    const regex = /(.*?\()([0-9]+)(.*)/gm;
    const str = `some data (920 seconds)
    Any other data(10101 minutes)
    Any other data(8918 hours)`;
    const subst = `$2`;
    
    // The substituted value will be contained in the result variable
    const result = str.replace(regex, subst);
    
    console.log('Substitution result: ', result);

    Python 测试

    # coding=utf8
    # the above tag defines encoding for this document and is for Python 2.x compatibility
    
    import re
    
    regex = r"(.*?\()([0-9]+)(.*)"
    
    test_str = ("some data (920 seconds)\n"
        "Any other data(10101 minutes)\n"
        "Any other data(8918 hours)")
    
    subst = "\\2"
    
    # You can manually specify the number of replacements by changing the 4th argument
    result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
    
    if result:
        print (result)
    
    # Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
    

    【讨论】:

      猜你喜欢
      • 2011-07-18
      • 2011-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-13
      • 1970-01-01
      • 2018-04-04
      相关资源
      最近更新 更多