Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.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,我想匹配两个正则表达式A和B,其中A和B显示为'AB'。然后我想在a和B之间插入一个空格,使其成为“a B” 例如,如果A=[0-9]和B=!+,我想做如下的事情 match = re.sub('[0-9]!+', '[0-9] !+', input_string) 但是,这显然不起作用,因为这将用字符串“[0-9]!+”替换任何匹配项 如何在正则表达式中实现这一点(最好是一行)?或者这需要几个繁琐的步骤吗?使用组 match = re.sub('([0-9])(!+)', r'\1 \2',

我想匹配两个正则表达式A和B,其中A和B显示为'AB'。然后我想在a和B之间插入一个空格,使其成为“a B”

例如,如果A=[0-9]和B=!+,我想做如下的事情

match = re.sub('[0-9]!+', '[0-9] !+', input_string)
但是,这显然不起作用,因为这将用字符串“[0-9]!+”替换任何匹配项

如何在正则表达式中实现这一点(最好是一行)?或者这需要几个繁琐的步骤吗?

使用组

match = re.sub('([0-9])(!+)', r'\1 \2', input_string);

\1
\2
表示第一个和第二个括号内的片段。前缀
r
用于保持
\
字符的完整性。

假设输入字符串为
“我有5G网络”
,但您希望在
5
G
之间留有空格,即每当出现
G20
AK47
等表达式时,您都希望将数字和字母分开(
我有5G网络
)。在这种情况下,您需要用另一个正则表达式替换正则表达式。类似如下:

re.sub(r'\w\d',r'\w\d',输入字符串)

但这不起作用,因为替换字符串不会保留第一个正则表达式捕获的字符串

解决方案:

它可以通过访问regex替换中的组来实现。如果您想向标记的组添加内容,此方法将非常有效

re.sub(r“(\..*$)”、r“\u BACK\1”、“my\u file.jpg”)
re.sub(r'(\d+)、r'\1'、“我有25美分”)

您也可以使用此方法通过捕获两组而不是一组来解决问题

re.sub(r“([A-Z])(\d)”,r“\1\2”,输入字符串)

另一种方法是:

re.sub(r“(\w\d)”,lambda d:d.group(0)[0]+''+d.group(0)[1],输入字符串)

另一种方法是使用look aheads:

re.sub(r)(?