【问题标题】:searching word following a giving pattern按照给定模式搜索单词
【发布时间】:2019-07-05 06:54:57
【问题描述】:

我想在字符串中得到'MASTER_INACTIVE'这个词:

'p_esco_link->state = MASTER_INACTIVE; /*M-t10*/'

通过搜索 reg-expression 'p_esco_link->state =' 找到以下单词。

我必须替换对 API 函数的日期访问。我在 python 3.6 中尝试了一些 reg-expression,但它不起作用。

pattern = '(?<=\bp_esco_link->state =\W)\w+'

if __name__ == "__main__":

    syslogger.info(sys.argv)

    if version_info.major != 3:

        raise Exception('Olny work on Python 3.x')

    with open(cFile, encoding='utf-8') as file_obj:
        lineNum = 0
        for line in file_obj:
            print(len(line))
            re_obj = re.compile(pattern)
            result = re.search(pattern, line)
            lineNum += 1
            #print(result)
            if result:
                print(str(lineNum) + ' ' +str(result.span()) + ' ' + result.group())

例外的Python re 模块可以找到'MASTER_INACTIVE' 的位置并将其放入result.group()。 错误信息是 Python re 模块什么也没找到。

【问题讨论】:

    标签: python python-3.x regex python-re


    【解决方案1】:

    您的模式运行良好,

    只需更改代码中的下面一行,

    pattern = r'(?<=\bp_esco_link->state =\W)\w+'  # add r prefix
    

    检查此示例工作,我将line 添加为您的字符串。

    import re
    
    pattern = r'(?<=\bp_esco_link->state =\W)\w+'
    line = 'p_esco_link->state = MASTER_INACTIVE; /*M-t10*/'
    
    re_obj = re.compile(pattern)
    result = re.search(pattern, line)
    
    print(result.span())  # (21, 36)
    print(result.group())  # 'MASTER_INACTIVE'
    

    查看以下问题以进一步了解'r'前缀,

    【讨论】:

    • 不客气@PopeB.Lei,请将此答案作为已接受的答案。这将有助于其他开发人员确定地选择最佳答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    相关资源
    最近更新 更多