這很簡單,但我使用正則表達式相對較新。我想更改以下字符串:“我愛貓”、“我愛狗”、“我愛貓”、“我愛狗”我只想知道在任何模式之前刪除空格的設(shè)置。在這種情況下,大寫字母。
1 回答

jeck貓
TA貢獻1909條經(jīng)驗 獲得超7個贊
您可以結(jié)合使用前瞻斷言re.sub():
import re
s = ' I love cats'
re.sub(r'''^ # match beginning of string
\s+ # match one or more instances of whitespace
(?=[A-Z]) # positive lookahead assertion of an uppercase character
''','',s,flags=re.VERBOSE)
并向您展示在小寫字母之前沒有刪除空格:
s = ' this is a test'
re.sub(r'^\s+(?=[A-Z])','',s)
結(jié)果:
' this is a test'
添加回答
舉報
0/150
提交
取消