[英]Finding adjacently repeated “and” in a sentence using regex?
我有一个字符串“ this is a boy and and and and and girl or biscut and pen ”我想用单个and
替换所有这些and
s。 这可以通过使用正则表达式来完成吗?
我正在使用这个正则表达式,但它失败了:
@"\b(?<word>\w+)\s+(\k<word>)\b"
如果您的意思是一般重复的单词(正如您帖子中的正则表达式所暗示的那样):
resultString = Regex.Replace(subjectString, @"\b(\w+)(?:\s+\1)+\b", "$1");
解释:
\b # Assert start at a word boundary
(\w+) # Match a word
(?: # Try to match...
\s+ # Whitespace and
\1 # the same word as before
)+ # one or more times
\b # Assert end at a word boundary
如果它只是and
您想替换:
resultString = Regex.Replace(subjectString, @"\b(?:and\s+){2,}", "and ");
可能是这样的: @"(\band\s+){2,}"
(虽然未经测试)。 或者,因为您无论如何都在搜索/替换,所以@"(\band\s+)+"
。
Regex.Replace(text, @"(\band\s+)+", "and ");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.