仅当pattern不在转义字符串内时,re.match才返回匹配对象

时间:2016-02-02 00:54:15

标签: python python-3.x

如果模式不在转义字符串中,我怎样才能获得匹配对象? 例如,给出字符串:

'my string \"string string inside of escaped string\" string string'

如何忽略转义字符串中的任何子字符串:

\"string inside of escaped string\"

并且只从未包含在转义字符串中的子字符串中获取匹配项?

E.G:

myString = 'my string string \"string inside of escaped string\" string string'

find_matches_not_escaped(myString)

返回

['mystring', 'mystring', 'mystring', 'mystring']

获得4场比赛而不是6场比赛? (即忽略转义字符串中的匹配。)

1 个答案:

答案 0 :(得分:2)

首先删除内部引用的字符串,然后搜索剩下的字符串:

>>> strippedstring = re.sub(r'"[^"]*"', '', myString)
>>> re.findall(r"\bstring", strippedstring)
['string', 'string', 'string', 'string']

如果需要,添加第二轮以删除单引号。如果需要实际的周围引号(它们可能影响单词边界等),请替换字符串'""'以使引号保留,但内容将被删除。

另一种允许你在重建原始字符串时改变匹配的方法是在引用的文本上进行拆分(使用捕获,以避免丢失它),改变结果中的偶数索引(未加引号的文本),然后加入它回到一起:

import itertools

# Puts the quoted strings in the odd indices and the unquoted in the even
splitstr = re.split(r'("[^"]*")', myString)

# Process only the even indices
for i, x in itertools.islice(enumerate(splitstr), None, None, 2):
    splitstr[i] = re.sub(r'\bstring', 'foo', x)

# Put it all back together and print
newstring = ''.join(splitstr)
print(newstring)

输出:

  

我的foo foo“转义字符串里面的字符串”foo foo