最后,我希望能够输入一个字符串,如“\mycard{front1}{back1}\mycard{front2}{back2}\mycard{front3}{back3}”,并返回每张卡的前后。
我在NSRegularExpression上找到了这个网站,但是我很难根据我的问题调整它。
这是我目前所拥有的。
import Foundation
func rangeFromNSRange(nsRange: NSRange, forString str: String) -> Range<String.Index>? {
let fromUTF16 = str.utf16.startIndex.advancedBy(nsRange.location, limit: str.utf16.endIndex)
let toUTF16 = fromUTF16.advancedBy(nsRange.length, limit: str.utf16.endIndex)
if let from = String.Index(fromUTF16, within: str), let to = String.Index(toUTF16, within: str) {
return from ..< to
}
return nil
}
do {
// let input = "My name is Taylor Swift"
// let regex = try NSRegularExpression(pattern: "My name is (.*)", options: NSRegularExpressionOptions.CaseInsensitive)
let input = "mycard{front}{back}"
let regex = try NSRegularExpression(pattern: "mycard{(.*)}{(.*)}", options: NSRegularExpressionOptions.CaseInsensitive)
let matches = regex.matchesInString(input, options: [], range: NSMakeRange(0, input.characters.count))
if let match = matches.first {
let range = match.rangeAtIndex(1)
if let swiftRange = rangeFromNSRange(range, forString: input) {
let name = input.substringWithRange(swiftRange)
}
}
} catch {
// regex was bad!
}
最佳答案
如我在评论中所述,您需要避开{
和}
。这将生成以下正则表达式:mycard\\{(.*)\\}\\{(.*)\\}
。
然后,您可能需要稍微更改匹配逻辑以输出预期结果:
if let match = matches.first {
for i in 1..<match.numberOfRanges {
let range = match.rangeAtIndex(i)
if let swiftRange = rangeFromNSRange(range, forString: input) {
let name = input.substringWithRange(swiftRange)
print(name)
}
}
}
哪些输出
前面
后面
如果要匹配多张卡,请使用以下正则表达式:
mycard\\{([^{]*)\\}\\{([^{]*)\\}
然后遍历匹配项
for match in matches {
for i in 1..<match.numberOfRanges {
let range = match.rangeAtIndex(i)
if let swiftRange = rangeFromNSRange(range, forString: input) {
let name = input.substringWithRange(swiftRange)
print(name)
}
}
}
对于输入
mycard{front}{back} mycard{front1}{back1}
来说,正确的输出是前面
后面
正面1
背面1