【问题标题】:RegEx fails to capture groups in loops [duplicate]RegEx 无法捕获循环中的组 [重复]
【发布时间】:2019-10-08 12:11:55
【问题描述】:

在 for 循环中使用正则表达式搜索时,无法从匹配对象中获取字符串。

row_values = result_script_name.split('^')
    for row in row_values:
        table_name = re.search(r"(?<=')(.*)(?=')", row).group(0)

AttributeError: 'NoneType' 对象没有属性 'group'

但同样的正则表达式模式在循环外使用时发现字符串非常好。

table_name = re.search(r"(?<=')(.*)(?=')", row_values[0]).group(0)

我想要的字符串是从字符串下面得到“生命周期”

^WORKFLOW_NAME='lifetime'

【问题讨论】:

    标签: python regex python-2.7 regex-lookarounds regex-group


    【解决方案1】:

    我相信正在发生的事情是某些行根本不匹配,因此您正在尝试访问一个甚至不存在的捕获组(在这种情况下是第零个)。这是您应该使用的模式:

    input = "^WORKFLOW_NAME='lifetime'"
    match = re.search(r"(?<=')(.*)(?=')", input)
    if match:
        print(match.group(0))
    

    也就是说,您应该首先检查对search 的调用是否成功,然后才能打印。我不知道你的循环应该做什么,但你可以很容易地根据你的需要调整上面的脚本。

    【讨论】:

    • 使用新的walrus 运算符(Python >= 3.8)你终于可以做某事了。喜欢if (match := re.search(...)) is not None:。耶! (好吧,PHP 从 1990 年开始就有这个了……)。
    【解决方案2】:

    在这里,我们可能想简化我们的表达方式,可能类似于:

    .+?'(.+?)'
    

    我们的数据保存在捕获组\\1的位置

    测试

    # coding=utf8
    # the above tag defines encoding for this document and is for Python 2.x compatibility
    
    import re
    
    regex = r".+'(.+?)'"
    
    test_str = "^WORKFLOW_NAME='lifetime'"
    
    subst = "\\1"
    
    # 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.
    

    DEMO

    正则表达式

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

    正则表达式电路

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

    演示

    const regex = /.+?'(.+?)'/gm;
    const str = `^WORKFLOW_NAME='lifetime'
    WORKFLOW_NAME='Any other data that we want'
    WORKFLOW_NAME='Any other data that we want'`;
    const subst = `$1`;
    
    // The substituted value will be contained in the result variable
    const result = str.replace(regex, subst);
    
    console.log('Substitution result: ', result);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多