繁体   English   中英

使用 re 删除大写字母前的空格

[英]Remove Whitespaces before Capital Letters using re

这很简单,但我使用正则表达式相对较新。 我想更改以下字符串:

“我爱猫”“我爱狗”“我爱猫”“我爱狗”

我只想知道在任何类型的模式之前删除空格的设置。 在这种情况下,大写字母。

您可以将前瞻断言与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)

结果:

' this is a test'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM