Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.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 - Fatal编程技术网

Python/Regex-仅在字符串末尾替换为模式

Python/Regex-仅在字符串末尾替换为模式,python,regex,Python,Regex,我需要替换字符串末尾的每个括号。我使用以下代码: a = '1 (FR) Product (IT, DE, ES)' b = re.sub(r' \((.*?)\)',r'', a) 但这将替换字符串中的每个括号。如何告诉python仅当模式位于字符串末尾时才替换它?捕获所有内容,但(之前的)和字符串末尾标识符$: >>> import re >>> a = '1 (FR) Product (IT, DE, ES)' >>> re.sub(

我需要替换字符串末尾的每个括号。我使用以下代码:

a = '1 (FR) Product (IT, DE, ES)'
b = re.sub(r' \((.*?)\)',r'', a)

但这将替换字符串中的每个括号。如何告诉python仅当模式位于字符串末尾时才替换它?

捕获所有内容,但
之前的
和字符串末尾标识符
$

>>> import re
>>> a = '1 (FR) Product (IT, DE, ES)'
>>> re.sub(r'\(([^(]*\))$', '', a)
'1 (FR) Product '

捕获所有内容,但
之前的
和字符串末尾标识符
$

>>> import re
>>> a = '1 (FR) Product (IT, DE, ES)'
>>> re.sub(r'\(([^(]*\))$', '', a)
'1 (FR) Product '
如果a[-1]=“a=a[:-2]
如果a[-1]=“a=a[:-2]
行得通