Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.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
Python 将正则表达式字符串传递到re.search_Python_Regex - Fatal编程技术网

Python 将正则表达式字符串传递到re.search

Python 将正则表达式字符串传递到re.search,python,regex,Python,Regex,在尝试将变量替换为搜索时,我被卡住了。 我使用以下代码从文件中收集存储的正则表达式并将其保存到变量“regex”。在本例中,存储的正则表达式用于从日志消息中查找带有端口号的ip地址 for line in workingconf: regexsearch = re.search(r'regex>>>(.+)', line) if regexsearch: regex = regexsearch.group(1) print reg

在尝试将变量替换为搜索时,我被卡住了。
我使用以下代码从文件中收集存储的正则表达式并将其保存到变量“regex”。在本例中,存储的正则表达式用于从日志消息中查找带有端口号的ip地址

for line in workingconf:
    regexsearch = re.search(r'regex>>>(.+)', line)
    if regexsearch:
        regex = regexsearch.group(1)
        print regex

#I use re.search to go through "data" to find a match.

data = '[LOADBALANCER] /Common/10.10.10.10:10'
alertforsrch = re.search(r'%s' % regex, data)
if alertforsrch:
    print "MATCH"
    print alertforsrch.group(1)
else:
    print "no match"
当这个程序运行时,我得到以下信息

$ ./messageformater.py
/Common/([\d]{1,}\.[\d]{1,}\.[\d]{1,}\.[\d]{1,}:[\d]{1,})
no match
当我将re.search更改为以下内容时,它会起作用。正则表达式将从该文件中获取,并且可能不是每次都相同。这就是我试图使用变量的原因

for line in workingconf:
    regexsearch = re.search(r'regex>>>(.+)', line)
    if regexsearch:
        regex = regexsearch.group(1)
        print regex


alertforsrch = re.search(r'/Common/([\d]{1,}\.[\d]{1,}\.[\d]{1,}\.[\d]{1,}:[\d]{1,})', data)
if alertforsrch:
    print "MATCH"
    print alertforsrch.group(1)
else:
    print "no match"

####### Results ########
$./messageformater.py
/Common/([\d]{1,}\.[\d]{1,}\.[\d]{1,}\.[\d]{1,}:[\d]{1,})
MATCH
10.10.10.10:10
对我来说很好

为什么还要麻烦使用字符串格式化程序呢?搜索(正则表达式,数据)应该可以正常工作


您可能在从文件中读入的正则表达式末尾有一个换行符-try re.search(regex.strip(),data)

您是否尝试在r“%s”%regex之后设置断点并将字符串与预期的字符串进行比较?可能有一些尾随空格或控制字符将匹配搞砸了。是的。有跟踪信息。Sharp3提供的答案解决了问题。谢谢。regex.strip()可以很好地工作。似乎正则表达式变量有一些尾随信息,导致正则表达式不匹配。谢谢你的帮助。