我有一个字符串形式的正则表达式列表(在解析作为搜索查询的自然语言文本后创建)。我现在想用它们来搜索文本。这是我现在的做法-
# given that regex_list=["r'((?<=[\W_])(%s\(\+\))(?=[\W_]|$))'", "r'((?<=[\W_])(activation\ of\ %s)(?=[\W_]|$))'"....]
sent='in this file we have the case of a foo(+) in the town'
gs1='foo'
for string_regex in regex_list:
mo=re.search(string_regex %gs1,sent,re.I)
if mo:
print(mo.group())
我需要的是能够使用这些字符串正则表达式,但也有 Python 的原始文字符号,就像我们都应该用于正则表达式查询一样。现在关于这些表达式 - 我有自然文本搜索命令,如 -
LINE_CONTAINS foo(+)
我使用 pyparsing 将其转换为正则表达式,例如基于语法的 r'((?<=[\W_])(%s\(\+\))(?=[\W_]|$))'。我将这些人类规则的列表发送到 pyparsing 代码,它会返回一个包含约 100 个这些正则表达式的列表。这些正则表达式以字符串格式构建。
这是生成这些字符串的代码的 MCVE 版本,这些字符串应该充当正则表达式 -
from pyparsing import *
import re
def parse_hrr(received_sentences):
UPTO, AND, OR, WORDS, CHARACTERS = map(Literal, "UPTO AND OR WORDS CHARACTERS".split())
LBRACE,RBRACE = map(Suppress, "{}")
integer = pyparsing_common.integer()
LINE_CONTAINS, PARA_STARTSWITH, LINE_ENDSWITH = map(Literal,
"""LINE_CONTAINS PARA_STARTSWITH LINE_ENDSWITH""".split()) # put option for LINE_ENDSWITH. Users may use, I don't presently
keyword = UPTO | WORDS | AND | OR | BEFORE | AFTER | JOIN | LINE_CONTAINS | PARA_STARTSWITH
class Node(object):
def __init__(self, tokens):
self.tokens = tokens
def generate(self):
pass
class LiteralNode(Node):
def generate(self):
return "(%s)" %(re.escape(''.join(self.tokens[0]))) # here, merged the elements, so that re.escape does not have to do an escape for the entire list
def __repr__(self):
return repr(self.tokens[0])
class ConsecutivePhrases(Node):
def generate(self):
join_these=[]
tokens = self.tokens[0]
for t in tokens:
tg = t.generate()
join_these.append(tg)
seq = []
for word in join_these[:-1]:
if (r"(([\w]+\s*)" in word) or (r"((\w){0," in word): #or if the first part of the regex in word:
seq.append(word + "")
else:
seq.append(word + "\s+")
seq.append(join_these[-1])
result = "".join(seq)
return result
class AndNode(Node):
def generate(self):
tokens = self.tokens[0]
join_these=[]
for t in tokens[::2]:
tg = t.generate()
tg_mod = tg[0]+r'?=.*\b'+tg[1:][:-1]+r'\b)' # to place the regex commands at the right place
join_these.append(tg_mod)
joined = ''.join(ele for ele in join_these)
full = '('+ joined+')'
return full
class OrNode(Node):
def generate(self):
tokens = self.tokens[0]
joined = '|'.join(t.generate() for t in tokens[::2])
full = '('+ joined+')'
return full
class LineTermNode(Node):
def generate(self):
tokens = self.tokens[0]
ret = ''
dir_phr_map = {
'LINE_CONTAINS': lambda a: r"((?:(?<=[\W_])" + a + r"(?=[\W_]|$))456", #%gs1, sent, re.I)",
'PARA_STARTSWITH':
lambda a: ("r'(^" + a + "(?=[\W_]|$))' 457") if 'gene' in repr(a) #%gs1, s, re.I)"
else ("r'(^" + a + "(?=[\W_]|$))' 458")} #,s, re.I
for line_dir, phr_term in zip(tokens[0::2], tokens[1::2]):
ret = dir_phr_map[line_dir](phr_term.generate())
return ret
## THE GRAMMAR
word = ~keyword + Word(alphas, alphanums+'-_+/()')
some_words = OneOrMore(word).setParseAction(' '.join, LiteralNode)
phrase_item = some_words
phrase_expr = infixNotation(phrase_item,
[
(None, 2, opAssoc.LEFT, ConsecutivePhrases),
(AND, 2, opAssoc.LEFT, AndNode),
(OR, 2, opAssoc.LEFT, OrNode),
],
lpar=Suppress('{'), rpar=Suppress('}')
) # structure of a single phrase with its operators
line_term = Group((LINE_CONTAINS|PARA_STARTSWITH)("line_directive") +
(phrase_expr)("phrases")) # basically giving structure to a single sub-rule having line-term and phrase
line_contents_expr = line_term.setParseAction(LineTermNode)
###########################################################################################
mrrlist=[]
for t in received_sentences:
t = t.strip()
try:
parsed = line_contents_expr.parseString(t)
temp_regex = parsed[0].generate()
mrrlist.append(temp_regex)
return(mrrlist)
基本上,代码是将正则表达式串在一起。然后我添加必要的参数,如 re.search 、 %gs1 等,以获得完整的正则表达式搜索查询。我希望能够使用这些字符串正则表达式进行搜索,因此我之前认为 eval() 会将字符串转换为其相应的 Python 表达式,这就是我使用它的原因 - 我错了。
TL;DR - 我基本上有一个字符串列表已在源代码中创建,我希望能够将它们用作正则表达式,< strong>使用 Python 的原始文字表示法。
请您参考如下方法:
您的问题似乎源于对原始字符串文字的作用及其用途的误解。没有神奇的原始字符串类型。原始字符串文字只是另一种创建普通字符串的方法。原始文字的解析方式略有不同。
例如,原始字符串r"\(foo\)" 也可以写成"\\(foo\\)"。双反斜杠告诉 Python 的常规字符串解析算法,您需要字符串中的实际反斜杠字符,而不是文字中的反斜杠作为转义序列的一部分,该转义序列被特殊字符替换。原始字符串算法没有额外的反斜杠,因为它从不替换转义序列。
但是,在这种特殊情况下,实际上不需要特殊处理,因为 \( 和 \) 在 Python 字符串中不是有意义的转义序列。当 Python 发现一个无效的转义序列时,它只是按字面意义包含它(反斜杠和所有)。所以你也可以使用 "\(foo\)"(没有 r 前缀)它也能正常工作。
但是依赖反斜杠被忽略通常不是一个好主意,因为如果您稍后编辑字符串,您可能会无意中添加 Python 确实理解的转义序列(当您真的想要原始的,未转换的版本)。由于 regex 语法有许多它自己的转义序列,它们在 Python 中也是转义序列(但具有不同的含义,例如 \b 和 \1),这是最好的练习始终使用原始字符串编写正则表达式模式,以避免在编辑它们时引入问题。
现在将其引入您展示的示例代码中。我完全不知道您为什么要使用 eval。据我所知,您无缘无故地在正则表达式模式周围错误地包含了额外的引号。您正在使用 exec 撤消包装。但是因为只有内部字符串使用原始字符串语法,所以当你 eval 它们时,如果你有任何麻烦的转义序列(the例如,外部字符串已经解析了 \b 并将其转换为 ASCII 退格字符 \x08)。
你应该撕掉 exec 代码并修复你的文字以避免额外的引号。这应该有效:
regex_list=[r'((?<=[\W_])(%s\(\+\))(?=[\W_]|$))', # use raw literals, with no extra quotes!
r'((?<=[\W_])(activation\ of\ %s)(?=[\W_]|$))'] # unnecessary backslashes?
sent='in this file we have the case of a foo(+) in the town'
gs1='foo'
for string_regex in regex_list:
mo=re.search(string_regex %gs1,sent,re.I) # no eval here!
if mo:
print(mo.group())
这个例子对我有用(它打印 foo(+))。请注意,您在第二个模式中(空格之前)有一些额外的不必要的反斜杠。这些是无害的,但可能会给复杂的主题增加更多的困惑(众所周知,正则表达式难以理解)。
