栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用正则表达式从文本中删除连续重复的单词并显示新文本

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用正则表达式从文本中删除连续重复的单词并显示新文本

首先,正则表达式

[aA-zZ]*
不会执行您认为的操作。这意味着“匹配零个或多个
a
S或字符ASCII之间的范围内
A
和ASCII
z
(其还包括
[
]
及其它),或
Z
S”。因此,它也匹配空字符串。

假设您只在寻找不重复的单词,该单词仅由ASCII字母组成,不区分大小写,保留第一个单词(这意味着您不希望匹配

"it's it's"
"oléolé!"
),那么您可以在单个regex操作中做到这一点:

String result = subject.replaceAll("(?i)\b([a-z]+)\b(?:\s+\1\b)+", "$1");

将会改变

Hello hello Hello there there past pastures

进入

Hello there past pastures

说明:

(?i)     # Mode: case-insensitiveb       # Match the start of a word([a-z]+) # Match one ASCII "word", capture it in group 1b       # Match the end of a word(?:      # Start of non-capturing group: s+     # Match at least one whitespace character 1      # Match the same word as captured before (case-insensitively) b      # and make sure it ends there.)+       # Repeat that as often as possible

看到它住在regex101.com。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/570532.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号