我有以下字符串。我只需要删除单引号之间的空格。其余部分在该行中应该完好无损
+amk=0 nog = 0 nf=1 par=1 mg =0.34e-6 sd='((nf != 1) ? (nf-1)) :0)' sca=0 scb=0 scc=0 pj='2* ((w+7.61e-6) + (l+8.32e-6 ))'
所以输出应该是
+amk=0 nog = 0 nf=1 par=1 mg =0.34e-6 sd='((nf!=1)?(nf-1)):0)' sca=0 scb=0 scc=0 pj='2*((w+7.61e-6)+(l+8.32e-6))'
是否可以使用单个Regex语句执行此操作?或需要多行?
答案 0 :(得分:1)
作为替代方案,您可能要考虑有限状态机。我总是忘记了该库,但是自行创建它非常简单。像这样:
def remove_quoted_whitespace(input_str):
"""
Remove space if it is quoted.
Examples
--------
>>> remove_quoted_whitespace("mg =0.34e-6 sd='((nf != 1) ? (nf-1)) :0)'")
"mg =0.34e-6 sd='((nf!=1)?(nf-1)):0)'"
"""
output = []
is_quoted = False
quotechars = ["'"]
ignore_chars = [' ']
for c in input_str:
if (c in ignore_chars and not is_quoted) or c not in ignore_chars:
output.append(c)
if c in quotechars:
is_quoted = not is_quoted
return ''.join(output)
另请参阅:Is list join really faster than string concatenation in python?