2017-06-06 66 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 | @Вася 
| 
相关问题