Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将regexp从perl转换为python_Python_Regex_Perl - Fatal编程技术网

如何将regexp从perl转换为python

如何将regexp从perl转换为python,python,regex,perl,Python,Regex,Perl,在Perl中: if ($test =~ /^id\:(.*)$/ ) { print $1; } 使用如下所述的RegexObject: 在Python中: import re test = 'id:foo' match = re.search(r'^id:(.*)$', test) if match: print match.group(1) 在Python中,正则表达式可以通过 字符串前面的r表示它是一个,这意味着反斜杠没有经过特殊处理(否则每个反斜杠都需要用另一

在Perl中:

 if ($test =~ /^id\:(.*)$/ ) {

 print $1;

 }

使用如下所述的RegexObject:

在Python中:

import re

test = 'id:foo'

match = re.search(r'^id:(.*)$', test)
if match:
    print match.group(1)
在Python中,正则表达式可以通过

字符串前面的
r
表示它是一个,这意味着反斜杠没有经过特殊处理(否则每个反斜杠都需要用另一个反斜杠转义,以便文字反斜杠进入regex字符串)

我在这里使用了
re.search
,因为这与Perl的
=~
操作符最接近。还有另一个函数
re.match
,它执行相同的操作,但只检查从字符串开头开始的匹配(与Perl程序员对“匹配”的定义相反)。有关两者之间差异的详细信息,请参阅


还请注意,没有必要转义
,因为它在正则表达式中不是一个特殊字符。

我编写了这个Perl-to-Python正则表达式转换器,当时我不得不将大量Perl正则表达式重写为Python的
re
包调用。它涵盖了一些基本内容,但在许多方面可能仍然有用:

match = re.match("^id:(.*)$", test)
if match:
    print match.group(1)
def convert_re (perl_re, string_var='column_name', 
                test_value=None, expected_test_result=None):
    '''
        Returns Python regular expression converted to calls of Python `re` library
    '''

    match = re.match(r"(\w+)/(.+)/(.*)/(\w*)", perl_re)

    if not match:
        raise ValueError("Not a Perl regex? "+ perl_re)

    if not match.group(1)=='s':
        raise ValueError("This function is only for `s` Perl regexpes (substitutes), i.e s/a/b/")

    flags = match.group(4)

    if 'g' in flags:
        count=0     # all matches
        flags=flags.replace('g','') # remove g
    else:
        count=1     # one exact match only

    if not flags:
        flags=0

    # change any group references in replacements like \2 to group references like \g<2>
    replacement=match.group(3)
    replacement = re.sub(r"\$(\d+)", r"\\g<\1>", replacement)

    python_code = "re.sub(r'{regexp}', r'{replacement}', {string}{count}{flags})".format(
                    regexp=match.group(2)
                ,   replacement=replacement
                ,   string=string_var
                ,   count=", count={}".format(count) if count else ''
                ,   flags=", flags={}".format(flags) if flags else ''
            )

    if test_value:
        print("Testing Perl regular expression {} with value '{}':".format(perl_re, test_value))
        print("(generated equivalent Python code: {} )".format(python_code))
        exec('{}=r"{}"; test_result={}'.format(string_var, test_value, python_code))
        assert test_result==expected_test_result, "produced={} expected={}".format(test_result, expected_test_result)
        print("Test OK.")

    return string_var+" = "+python_code

print convert_re(r"s/^[ 0-9-]+//", test_value=' 2323 col', expected_test_result='col')

print convert_re(r"s/[+-]/_/g", test_value='a-few+words', expected_test_result='a_few_words')
def convert\u re(perl\u re,string\u var='column\u name',
测试值=无,预期测试结果=无):
'''
返回转换为Python`re`库调用的Python正则表达式
'''
match=re.match(r“(\w+)/(.+)/(.*)/(\w*)”,perl\u-re)
如果不匹配:
raise VALUERROR(“不是Perl正则表达式?”+Perl\u re)
如果不匹配。组(1)='s':
raise VALUERROR(“此函数仅适用于`s`Perl regexpes(替代品),即s/a/b/”)
标志=匹配。组(4)
如果标志中有“g”:
计数=0#所有匹配项
标志=标志。替换('g','')#移除g
其他:
计数=1#仅一个精确匹配
如果没有标记:
标志=0
#将替换中的任何组引用(如\2)更改为组引用(如\g)
替换=匹配。组(3)
替换=re.sub(r“\$(\d+),r“\\g”,替换)
python_code=“re.sub(r'{regexp}',r'{replacement}',{string}{count}{flags})”.format(
regexp=match.group(2)
,替换=替换
,string=string\u var
,count=“,count={}”。如果count else'',则格式化(count)
,flags=“,flags={}”。如果标志为else,则格式化(标志)
)
如果测试_值:
打印(“使用值“{}”测试Perl正则表达式{}:”。格式(Perl_re,test_value))
打印(((生成的等效Python代码:{})。格式(Python_代码))
exec(“{}=r”{};测试结果={}”。格式(字符串变量、测试值、python代码))
断言测试结果==预期测试结果,“生成={}预期={}”。格式(测试结果,预期测试结果)
打印(“测试正常”)
返回字符串\u var+“=”+python\u代码
打印转换(r“s/^[0-9-]+/”,测试值='2323列',预期测试结果='列')
打印转换(r“s/[+-]/\ug/g”,测试值='a-now+words',预期测试结果='a\u now\u words')