2017-06-06 40 views

回答

1

嘗試正則表達式:@\p{L}+(?:$|\n)

\p{L} -> Match matches any kind of letter from any language 
$  -> Match End of the string 

現場演示:https://regex101.com/r/m9du5M/2

+2

這個正則表達式 - 「@ \ w + $' - 不僅與ASCII字母匹配,因爲ICU速記類支持Unicode。此外,它將匹配字符串末尾的「@_____」。更多的,這個正則表達式將打印* true *作爲像''@Вася\ n「'這樣的字符串。提到後面跟着一個換行符,而不是在字符串的最後。 '@ \ w + $'是**錯誤的解決方案**。 @Ashraful,修復或刪除請。 –

+0

@WiktorStribiżew很好的捕獲。 –

+0

順便說一句,提供鏈接到PCRE演示並不能證明正則表達式的工作原理,regex101.com不支持ICU正則表達式。 –

1

如果您想驗證用模式的用戶提字符串,您在說明顯示它是最好寫入String的擴展名。這將驗證數據。

嘗試:

extension String { 
    func mention() -> Bool { 
     let pattern = "@[a-zA-Z]+$" 
     guard let _ = self.range(of:pattern, options: .regularExpression) else { 
      return false 
     } 
     return true 
    } 
} 

測試用例:

let input = ["Hello @john", "Hello @john ", "Hello @john.", "Hello @john i,", "@_____", "@Вася\n"] 

for item in input { 
    if !item.mention() { 
     print("Failed to get mention at | \(item) |") 
    } 
} 

驗證:

Failed to get mention at | Hello @john | 
Failed to get mention at | Hello @john. | 
Failed to get mention at | Hello @john i, | 
Failed to get mention at | @_____ | 
Failed to get mention at | @Вася 
| 
相關問題