我在这里检查了很多类似的问题,这些问题的答案似乎对我来说不是一个可行的解决方案。我正在将格式化文件读入字符串 "Substring #1: Hello World!; Substring #2: My name is Tom; Substring #X: This is another substring"
。我需要找到 Substring #1
的索引要打印其内容( Hello World!
),稍后在代码中我需要打印 Substring #2
的内容( My name is Tom
) 等等。
到目前为止我已经尝试过:
String.index(of: subString)
- Xcode 错误:
Cannot convert value of type 'String' to expected argument type 'Character'
String.firstIndex(of: subString)
- Xcode 错误:`
Cannot convert value of type 'String' to expected argument type 'Character'
执行此操作的有效方法是什么?
最佳答案
您可以使用正则表达式来匹配您的字符串,假设所有子字符串都以 ;
或字符串结尾结尾。
这是您应该使用的正则表达式:
Substring #(\d+): (.+?)(?:;|$)
它将子字符串编号捕获到组 1 中,将子字符串捕获到组 2 中。
你可以像这样使用它:
extension String {
func substring(withNSRange range: NSRange) -> String {
return String(string[Range(range, in: self)!])
}
}
let string = "Substring #1: Hello World!; Substring #2: My name is Tom"
let regex = try! NSRegularExpression(pattern: "Substring #(\\d+): (.+?)(?:;|$)", options: [])
let matches = regex.matches(in: string, options: [], range: NSRange(location: 0, length: string.utf16.count))
let tuples = matches.map { (Int(string.substring(withNSRange: $0.range(at: 1))), string.substring(withNSRange: $0.range(at: 2))) }
let dict = Dictionary(uniqueKeysWithValues: tuples)
// dict will contain something like [1: Hello World!, 2: My name is Tom]
编辑:
假设子字符串的自定义结尾存储在名为 customStringEnd
的变量中,您可以像这样创建正则表达式:
let regex = try! NSRegularExpression(pattern: "Substring #(\\d+): (.+?)(?:\(NSRegularExpression.escapedPattern(for: customStringEnd))|$)", options: [])
关于 swift 4 : return Substring index from a String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54520418/