Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.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中的Regex替换为负前瞻_Python_Regex_Negative Lookahead - Fatal编程技术网

Python中的Regex替换为负前瞻

Python中的Regex替换为负前瞻,python,regex,negative-lookahead,Python,Regex,Negative Lookahead,我正在尝试删除规则文本周围的单引号。例如,给定列表: alist = ["'ABC'", '(-inf-0.5]', '(4800-20800]', "'\\'(4.5-inf)\\''", "'\\'(2.75-3.25]\\''"] 我想将“ABC”改为“ABC”,但保留其他引号,即: alist = ["ABC", '(-inf-0.5]', '(4800-20800]', "'\\'(4.5-inf)\\''", "'\\'(2.75-3.25]\\''"] 我尝试使用look he

我正在尝试删除规则文本周围的单引号。例如,给定列表:

alist = ["'ABC'", '(-inf-0.5]', '(4800-20800]', "'\\'(4.5-inf)\\''", "'\\'(2.75-3.25]\\''"]
我想将“ABC”改为“ABC”,但保留其他引号,即:

alist = ["ABC", '(-inf-0.5]', '(4800-20800]', "'\\'(4.5-inf)\\''", "'\\'(2.75-3.25]\\''"]
我尝试使用look head,如下所示:

fixRepeatedQuotes = lambda text: re.sub(r'(?<!\\\'?)\'(?!\\)', r'', text)
print [fixRepeatedQuotes(str) for str in alist]

还有其他解决办法吗?提前多谢

尝试应该有效:

result = re.sub("""(?s)(?:')([^'"]+)(?:')""", r"\1", subject)
解释

"""
(?:         # Match the regular expression below
   '           # Match the character “'” literally
)
(           # Match the regular expression below and capture its match into backreference number 1
   [^'"]       # Match a single character NOT present in the list “'"”
      +           # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
(?:         # Match the regular expression below
   '           # Match the character “'” literally
)
"""

re.sub
接受函数作为替换文本。所以,

re.sub(r"'([A-Za-z]+)'", lambda match: match.group(), "'ABC'")
屈服

"ABC"

你想让
“\\'(4.5-inf)\\''”
产生什么?好的,那么你对“常规文本”的定义是什么?字母数字A-Z?谢谢Joel,它解决了我的问题。应该是match.group(1)。@Eric:我想你把
.group()
groups()
搞混了。(参考上述评论。)
"ABC"