我有一个表达式,我需要删除运算符之间的空格。 例如 Rule_expr = ( '姓名' in ( "abc","bcd" )) 和 ( '年龄' < = 60 ). Here I need to remove space between '<='. The expression varies each time. I need a general statement to remove space between any 2 operators (<>=!).
我使用 shlex.shlex() 来塑造表达式,但它在运算符之间放置了空格,并且表达式失败。我需要删除它们之间的空间。
这是可以做到的:
import re
def remove_operator_spaces(expression):
operators = ['<', '>', '=', '!']
pattern = r'\s*([{}])\s*'.format(''.join(re.escape(op) for op in operators))
return re.sub(pattern, '\\1', expression)
expression = """\
( 'name' in ( "abc","bcd" )) and ( 'age' < = 60 and 'age' > = 13)"""
res = remove_operator_spaces(expression)
print(res)
输出:
( 'name' in ( "abc","bcd" )) and ( 'age'<=60 and 'age'>=13)
我们来解释一下
remove_operator_spaces
函数:
\s*
:匹配零个或多个空白字符。
([{}])
:这是一个匹配一个字符的捕获组。 {}
是一个占位符,将被连接的运算符替换。它捕获任何一个指定的运算符,例如。 <
,=
。
''.join(re.escape(op) for op in operators)
:这部分通过迭代operators
列表中的每个运算符并转义任何特殊字符来生成字符串。其工作原理如下:
re.escape(op) for op in operators
是一个生成器表达式,它迭代运算符列表中的每个运算符,并应用 re.escape
函数来转义运算符中存在的任何特殊字符。 re.escape
函数确保运算符被视为正则表达式中的文字字符。''.join(...)
:这会将转义运算符连接成一个不带分隔符的字符串。例如,如果运算符列表为 ['<', '>', '=', '!']
,则结果将为 '<>=!'
。
'\\1'
:这是替换字符串。 \\1
指的是模式中第一个捕获的组。在我们的例子中,捕获的组是没有周围空间的运算符。通过使用 \\1
作为替换,我们可以有效地仅用捕获的运算符替换匹配的模式。