swift中的正则表达式

Dam*_*dar 5 regex regex-group nsregularexpression regex-greedy swift

我对 swift 中的 NSRegularExpression 有点困惑,有人可以帮助我吗?

任务:1给出("name","john","name of john")
那么我应该得到["name","john","name of john"]. 在这里我应该避免使用括号。

任务:2给出("name"," john","name of john")
那么我应该得到["name","john","name of john"]. 在这里我应该避免括号和额外的空格,最后得到字符串数组。

任务:3给出key = value // comment
那么我应该得到["key","value","comment"]. 在这里,我应该通过避免只获取行中的字符串,=并且//
我已经尝试了下面的任务 1 代码但没有通过。

let string = "(name,john,string for user name)"
let pattern = "(?:\\w.*)"

do {
    let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
    let matches = regex.matches(in: string, options: [], range: NSRange(location: 0, length: string.utf16.count))
    for match in matches {
        if let range = Range(match.range, in: string) {
            let name = string[range]
            print(name)
        }
    }
} catch {
    print("Regex was bad!")
}
Run Code Online (Sandbox Code Playgroud)


提前致谢。

Raj*_*r R 2

使用除空格之外的非字母数字字符分隔字符串。然后用空格修剪元素。

extension String {
    func words() -> [String] {
        return self.components(separatedBy: CharacterSet.alphanumerics.inverted.subtracting(.whitespaces))
                .filter({ !$0.isEmpty })
                .map({ $0.trimmingCharacters(in: .whitespaces) })
    }
}

let string1 = "(name,john,string for user name)"
let string2 = "(name,       john,name of john)"
let string3 = "key = value // comment"

print(string1.words())//["name", "john", "string for user name"]
print(string2.words())//["name", "john", "name of john"]
print(string3.words())//["key", "value", "comment"]
Run Code Online (Sandbox Code Playgroud)

  • 请记住,此解决方案对于字符串 3 中的许多可能的值都会失败。对于任何带有连字符、撇号或其他标点符号的名称,它也可能会失败。 (3认同)

归档时间:

查看次数:

3900 次

最近记录:

6 年,5 月 前