簡體   English   中英

使用正則表達式在句子中找到相鄰重復的“和”?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM