问题描述
我需要通过在 (if) 语句中为字符串中的每个字符提供两种可能性来比较字符串,例如:
I need to compare a string by giving two possibilities for each character in the string in an (if) statement eg:
let str = "2 3 1 2"
if str == "(1||2) (2||3) (1||2) (1||2)" {
//Do Something
}
我知道代码写得不正确,但只是为了理解我的意思.
I know the code is not written correctly, but just to understand what I mean.
我曾经在 VB 中使用 (Like Operator) 例如:
I used to use (Like Operator) in VB eg:
Dim s As String = "2 3 1 2"
If s Like "[1-2] [3-4] [2-3] [1-2]" Or s Like "[1-2] [1-2] [2-3] 2" Then
//Do something
End If
我在 swift 中找不到类似的东西.
I couldn't find anything similar in swift.
请帮忙,谢谢.
推荐答案
您描述的问题迫切需要使用 正则表达式.
The problem you describe is crying out to solved using regular expressions.
上次我查看时,Swift 不支持正则表达式,但它允许使用 NSRegularExpression
.请参阅Swift 中的正则表达式 以正则表达式类为例.
Last time I looked, Swift did not support regular expressions, but it does allow use of NSRegularExpression
. See Regex in Swift for an example of a Regex class.
所以你最终会写出类似的东西
So you'd end up writing something like
if Regex("[12] [23] [12] [12]").test("2 3 1 2") {
println("matches pattern")
}
关于此主题的另一篇博文是清洁正则表达式在 Swift 中.
Another blog post on this topic is Clean Regular Expressions In Swift.
这篇关于通过为 Swift 中的每个字符提供两种可能性来比较字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!