Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.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正则表达式_Python_Regex - Fatal编程技术网

基本Python正则表达式

基本Python正则表达式,python,regex,Python,Regex,我试图替换单个字母后面跟一个=符号的每个实例,后面跟一个在=和字母之间有空格的字母。因此,h=e将替换为h=e。这就是我现在拥有的: definition = 'h=e' definition = re.sub(r"\w=\w", r"\w\s=\s\w", definition) 但这会产生\w\s=\s\w而不是h=e。我做错了什么?改变 re.sub(r"\w=\w", r"\w\s=\s\w", definition) 到 re.sub(r'(\w)=(\w'),r“\g=\g”,定

我试图替换单个字母后面跟一个=符号的每个实例,后面跟一个在=和字母之间有空格的字母。因此,
h=e
将替换为
h=e
。这就是我现在拥有的:

definition = 'h=e'
definition = re.sub(r"\w=\w", r"\w\s=\s\w", definition)
但这会产生
\w\s=\s\w
而不是
h=e
。我做错了什么?

改变

re.sub(r"\w=\w", r"\w\s=\s\w", definition)

re.sub(r'(\w)=(\w'),r“\g=\g”,定义)

替换项不应是另一个正则表达式,而应是普通字符串(或函数)

返回通过替换repl替换字符串中模式最左侧不重叠的出现而获得的字符串。如果找不到模式,则返回的字符串将保持不变repl可以是字符串或函数

例如:

definition = 'h=e'
definition = re.sub(r"(\w)=(\w)", "\g<1> = \g<2>", definition)
print(definition)

您可以避免使用字符串中不希望替换的部分,但仍然可以通过使用lookahead/lookahead断言来断言它周围的部分与某些内容匹配

>>> re.sub(r"(?<=\w)=(?=\w)", " = ", "h=e")
'h = e'
>>re.sub(r)(?的文件特别提到

诸如
\&
之类的未知转义被忽略

替换中只需要一个文本空格。
\s
在这里没有意义。您还需要向表达式中添加组,以捕获替换中不希望替换的部分:

反向引用(如
\6
)将替换为模式中与组6匹配的子字符串

您的替换应该如下所示:

definition = re.sub(r"(\w)=(\w)", r"\1 = \2", definition)

如果您在替换中指的是空格,请使用空格,而不是表示“任何类型的空格”的正则表达式。re.sub中的替换显式允许引用原始匹配中的捕获组的反向引用。谢谢。
definition = 'h=e'
definition = re.sub(r"\b=\b", " = ", definition)
print(definition)
>>> re.sub(r"(?<=\w)=(?=\w)", " = ", "h=e")
'h = e'
>>> re.sub(r"(?<=x)=(?=y)", " = ", "y=z z=q y=x x=y a=b")
'y=z z=q y=x x = y a=b'
definition = re.sub(r"(\w)=(\w)", r"\1 = \2", definition)