如何用Python正则将字符串中相邻重复模式替换为单个元素
解决连续重复
user的替换问题 为什么你之前的正则不对
你用的[user\s]+是字符类匹配,它会把u、s、e、r、空格当成独立的单个字符,匹配任意这些字符的连续组合,所以才会得到那些零散混乱的结果,完全不符合“匹配连续重复的user单词”的需求。
正确的正则替换方案
要把连续相邻的user(不管重复多少次)替换成单个user,可以用下面的代码:
import re # 示例文本1 text1 = 'user user please sort situation time bound manner present officer ha moral courage to interest of public of expect political leadership order always absolutely right thing http' result1 = re.sub(r'(\buser\s+)(?:\1)+', r'\1', text1) print(result1) # 示例文本2 text2 = 'user user user please user user sort situation time bound manner present officer ha moral courage to interest of public of expect political leadership order always absolutely right thing http' result2 = re.sub(r'(\buser\s+)(?:\1)+', r'\1', text2) print(result2)
正则表达式拆解(新手友好版)
r'(\buser\s+)(?:\1)+' 各部分作用:
\b:单词边界,确保只匹配独立的user单词,不会误匹配username这类包含user的其他单词(user\s+):捕获组1,匹配user加上一个或多个空格(\s+兼容多个空格的情况)(?:\1)+:非捕获组,\1是对捕获组1内容的引用,+表示这个组至少重复1次——也就是匹配一个或多个和组1完全一样的user+空格组合- 替换为
\1:把整个连续重复的user+空格序列,替换成单个组1的内容(也就是user+空格)
输出结果
- 示例1输出:
user please sort situation time bound manner present officer ha moral courage to interest of public of expect political leadership order always absolutely right thing http - 示例2输出:
user please user sort situation time bound manner present officer ha moral courage to interest of public of expect political leadership order always absolutely right thing http
内容的提问来源于stack exchange,提问作者Indrajeet Singh Yadav
相关产品推荐
相关产品推荐

