我正在尝试将看起来像这样的字符串替换( self, False )
为(self, False)
. 我正在使用的正则表达式:
s = re.compile('\(\s*(.*)\s*\)')
s.sub(r'(\1)', '( self, False )')
哪个返回(self, False )
如何在没有尾随空格的情况下捕获括号内的组?
我正在尝试将看起来像这样的字符串替换( self, False )
为(self, False)
. 我正在使用的正则表达式:
s = re.compile('\(\s*(.*)\s*\)')
s.sub(r'(\1)', '( self, False )')
哪个返回(self, False )
如何在没有尾随空格的情况下捕获括号内的组?
为什么不使用字符串替换来消除带有空字符的空格
str = '( self, False )'
print(str.replace(' ',''))
#(self,False)
尝试这个:
#TEST 1
>>> import re
>>> str = '( self, False )'
>>> re.sub(r'(\()([\s]*?)((?:[\S]+?[\s]*?(?!\))+[\S]*?)|(?:[\S]+?(?=[\s]*?\))))([\s]*?)(\))', r'\1\3\5', str)
#OUTPUT
'(self, False)'
#TEST 2
>>> str = '''TEbh eyendd dkdkmfkf( self, False ) dduddnudmd ( self, False )
( self, False ) fififfj m( self, False )kmiff ikifkifko kfmimfimfifi k
fkmfikfk kfmifm ( self, False ) fififi,fo'''
>>> print(re.sub(r'(\()([\s]*?)((?:[\S]+?[\s]*?(?!\))+[\S]*?)|(?:[\S]+?(?=[\s]*?\))))([\s]*?)(\))', r'\1\3\5', str))
#OUTPUT
'TEbh eyendd dkdkmfkf(self, False) dduddnudmd (self, False)
(self, False) fififfj m(self, False)kmiff ikifkifko kfmimfimfifi k
fkmfikfk kfmifm (self, False) fififi,fo'
#TEST 3
>>> '''TEbh eyendd dkdkmfkf( self) dduddnudmd ( self)
( self, False ) fififfj m( self, False)kmiff ikifkifko kfmimfimfifi k
fkmfikfk kfmifm ( self, False ) fififi,fo
(self ) dndnd (self ) fufufjiri ( self ) (self ) ( self)( self)(self )( self )(self )( self )'''
>>> print(re.sub(r'(\()([\s]*?)((?:[\S]+?[\s]*?(?!\))+[\S]*?)|(?:[\S]+?(?=[\s]*?\))))([\s]*?)(\))', r'\1\3\5', str))
#OUTPUT
TEbh eyendd dkdkmfkf(self) dduddnudmd (self)
(self, False) fififfj m(self, False)kmiff ikifkifko kfmimfimfifi k
fkmfikfk kfmifm (self, False) fififi,fo
(self) dndnd (self) fufufjiri (self) (self) (self)(self)(self)(self)(self)(self)
捎带您的简单解决方案:
>>> '''TEbh eyendd dkdkmfkf( self) dduddnudmd ( self)
( self, False ) fififfj m( self, False)kmiff ikifkifko kfmimfimfifi k
fkmfikfk kfmifm ( self, False ) fififi,fo
(self ) dndnd (self ) fufufjiri ( self ) (self ) ( self)( self)(self )( self )(self )( self )'''
>>> print(re.sub(r'(\()\s*([\S\s]*?)\s*(\))', r'\1\2\3', str))
#OUTPUT
TEbh eyendd dkdkmfkf(self) dduddnudmd (self)
(self, False) fififfj m(self, False)kmiff ikifkifko kfmimfimfifi k
fkmfikfk kfmifm (self, False) fififi,fo
(self) dndnd (self) fufufjiri (self) (self) (self)(self)(self)(self)(self)(self)
找到了一个简单的解决方案。
s = re.compile('\(\s*(.*?)\s*\)')
s.sub(r'(\1)', 'hi hello ble ble ( self, False ) ( self ) (self , greedy ) ( hello)')
#Output
'hi hello ble ble (self, False) (self) (self , greedy) (hello)'
根据 python re 文档:
' '、'+' 和 '?' 限定符都是贪婪的;它们匹配尽可能多的文本。有时这种行为是不希望的;如果 RE <. > 匹配'b',它将匹配整个字符串,而不仅仅是''。添加 ? 在预选赛使其以非贪婪或最低限度的方式执行比赛之后;将匹配尽可能少的字符。使用 RE <.*?> 将仅匹配 ''。