[英]python: Replace/substitute all whole-word match in a string
我们假设我的字符串是"#big and #small, #big-red, #big-red-car and #big"
如何使用re.sub(), re.match(), etc.
将一个标签替换为单词?
例如,所有#big
必须更改为BIG,但#big-red
和#big-red-car
不应该受到影响。
让我们定义你的字符串:
>>> s = "#big and #small, #big-red, #big-red-car and #big"
现在,让我们做你的替换:
>>> import re
>>> re.sub(r'#big([.,\s]|$)', r'#BIG\1', s)
'#BIG and #small, #big-red, #big-red-car and #BIG'
正则表达式#big([.,\\s]|$)
将匹配所有#big
字符串,后跟句点,逗号,空格或行尾。 如果在#big
之后您认为其他字符可以接受,则应将它们添加到正则表达式中。
如果我们想要有点发烧友,我们可以使用#big
断言(?=...)
,以确保#big
是可以接受的:
>>> re.sub(r'#big(?=[.,\s]|$)', r'#BIG', s)
'#BIG and #small, #big-red, #big-red-car and #BIG'
为了测试当#big
具有“之后的逗号或句点”时,这可以正常工作,让我们创建一个新字符串:
>>> s = "#big and #big, #big. #small, #big-red, #big-red-car and #big"
而且,让我们测试一下:
>>> re.sub(r'#big(?=[.,\s]|$)', r'#BIG', s)
'#BIG and #BIG, #BIG. #small, #big-red, #big-red-car and #BIG'
此信息是一种单向边界技巧。
使用负面看后面/前面的断言,
在特定方向内,它会让BEGIN / END字符串匹配,
但不允许其他人匹配。
这导致了一些有趣的组合场景
负面构造在一个类中,涵盖了无穷无尽的范围
字符,但允许您排除其中的一些单个字符
那个范围。
要使用的典型构造是否定类。
\\D
- 非数字课程
\\S
- 非空白类
\\W
- 非Word课程
\\PP
- 非标点属性类
\\PL
- 非字母属性类
由于它们用于否定断言,因此反转实际上是
正在寻找的人物。
\\d, \\s, \\w, \\pP, \\pL
分别
权力源于它们可以结合在一起的事实
一个戏剧效果的课程 。
如果将单个字符添加到类中,则将其排除,不允许使用。
实际上,它创建了类减法 。
创建类时的规则是:
\\D
, \\PP
等...) \\n
, =
等等) 减法示例: (?![\\S\\r\\n])
将是一个需要的前瞻边界
只有水平空格,在某些引擎中,表示为
\\h
构造。
在你的例子中,边界将是这样的。
(?<![\\S\\PP-])#big(?![\\S\\PP-])
打破它
(?<! # Boundary - Behind direction
[\S\PP-] # Need all whitespace and punctuation, but not the '-'
)
\#big
(?! # Boundary - Ahead direction
[\S\PP-] # Need all whitespace and punctuation, but not the '-'
)
添加到类中的每个文字字符实际上都是排除的
它来自匹配。
这称为类减法 。
测试用例
输入#big and #small, #big, #big, #big-red, #big-red-car and #big
产量
** Grp 0 - ( pos 0 , len 4 )
#big
** Grp 0 - ( pos 17 , len 4 )
#big
** Grp 0 - ( pos 23 , len 4 )
#big
** Grp 0 - ( pos 56 , len 4 )
#big
基本上,符合这些只是#big
和#small, #big
, #big
,#大红色,#大红色车和#big
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.