目標:我想要一個正則運算式來搜索字串中所有大寫單詞/名稱的首字母。如果單詞長度為 4 個或更多字符,則將這些大寫單詞替換為“Whatever”。然后用“whatever”替換4個或更多小寫字母的單詞。
字串輸入:
let myString = "This is a regular string. How does this Work? Does any Name know How?"
所需的字串輸出:
let myString = "Whatever is a whatever whatever. How whatever this Whatever? Whatever any Whatever whatever whatever How?"
我試過的:
let myString = "This is a regular string. How does this Work? Does any Name know How?"
let x = myString.replacingOccurrences(of: "\\b\\p{Lu}{4,}\\b",
with: "Whatever",
options: .regularExpression)
let finalX = x.replacingOccurrences(of: "\\b\\p{L}{4,}\\b",
with: "whatever",
options: .regularExpression)
print(finalX)
問題:
第一個檢查是大寫字母,第二個是小寫字母,但它仍然回傳全部小寫。
有人知道如何用我所擁有的來解決這個問題嗎?
uj5u.com熱心網友回復:
您想要的正則運算式如下:
\b[A-Z][a-z]{3,}\b
這僅適用于基本字母 AZ 和 az。如果你想完全支持任何字母,那么你需要這樣的東西:
\b\p{Lu}\p{Ll}{3,}\b
\b 表示“單詞邊界”。\p{Lu} 表示“大寫字母”。\p{Ll} 表示“小寫字母”。
您只想在呼叫replacingOccurrences. 幾乎沒有理由使用contains. 這將尋找您傳入的文字文本,當然您使用的正則運算式不會在字串中作為文字文本找到。
let myString = "This is a regular string. How does this Work? Does any Name know How?"
let x = myString.replacingOccurrences(of: "\\b\\p{Lu}\\p{Ll}{3,}\\b",
with: "Whatever",
options: .regularExpression)
print(x)
輸出:
無論是常規字串。這是怎么回事?隨便 隨便 知道 怎么辦?
要做到這兩點,您還需要"\\b\\p{Ll}{4,}\\b".
以下更改兩組。
let myString = "This is a regular string. How does this Work? Does any Name know How?"
let x = myString
.replacingOccurrences(of: "\\b\\p{Ll}{4,}\\b",
with: "whatever",
options: .regularExpression)
.replacingOccurrences(of: "\\b\\p{Lu}\\p{Ll}{3,}\\b",
with: "Whatever",
options: .regularExpression)
print(x)
輸出:
隨便就是隨便。怎么 怎么 怎么 怎么 怎么 怎么 隨便 隨便 隨便 怎么樣?
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/528904.html
