swift 4 : return Substring index from a String

标签 swift string

我在这里检查了很多类似的问题,这些问题的答案似乎对我来说不是一个可行的解决方案。我正在将格式化文件读入字符串 "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/

相关文章:

arrays - 在 Ruby 中,如何返回数组中具有相同字符串值的元素的所有索引值?

string - 将数字的日期格式与其他文本合并为一个字符串

c - 为什么 getchar() 没有收到任何输入?

ios - 从父类(super class)调用由子类实现的协议(protocol)方法

ios - 应用内购买错误,始终 myProduct 为 0

ios swift - 从多个选项卡实例化相同的 VC

java - 从字符串中删除重音

c - 句子中的字数统计 - C 程序

ios - 两个 TableView ,两个模型

ios - 在我的 Swift 4 代码中调用 setValuesForKeys 失败