2024-04-25 22:06:50 发布
网友
如何在python中使用regex删除与句点相连的单词。 ex: for a string 'random random 123.4445.764 random goo.34.hi random',操作返回'random random random random'
ex: for a string 'random random 123.4445.764 random goo.34.hi random'
'random random random random'
不使用regex的替代方法:
" ".join(s for s in string.split() if '.' not in s) #'random random random random'
要匹配与句点相关的单词,可以使用:
^{}
更新了来自@Jan的注释
细节
\b
\w+
(?:
\.\w+
)+
a.b
a.b.c
\s*
例如:
import re str = 'random random 123.4445.764 random goo.34.hi random' print(re.sub("\\b\w+(?:\.\w+)+\s*", "", str))
这会给你:
random random random random
Demo Python
使用re.sub
re.sub
演示:
import re s = 'random random 123.4445.764 random goo.34.hi random' print(re.sub("\w*\.\w*", "", s))
输出:
不使用regex的替代方法:
要匹配与句点相关的单词,可以使用:
^{}
更新了来自@Jan的注释
细节
\b
词边界\w+
匹配一个或多个单词字符(?:
非捕获群\.\w+
匹配一个点和一个或多个单词字符)+
关闭非捕获组并重复一次或多次以匹配a.b
或a.b.c
等\s*
零次或多次匹配空白字符。你知道吗例如:
这会给你:
Demo Python
使用
re.sub
演示:
输出:
相关问题 更多 >
编程相关推荐