Regex 返回字符串的所有匹配项
我试图找出如何从一个更大的字符串中获取字符串的每个匹配项 较大字符串的示例:Regex 返回字符串的所有匹配项,regex,macos,cocoa,swift,Regex,Macos,Cocoa,Swift,我试图找出如何从一个更大的字符串中获取字符串的每个匹配项 较大字符串的示例: "xmp_id": 3243041, "certified": 1,"xmp_id": 3243042, "certified": 1,"xmp_id": 3243043, "certified": 1,"xmp_id": 3243044, "certified": 1,"xmp_id": 3243045, "certified": 1,"xmp_id": 3243046, "certified": 1,
"xmp_id": 3243041, "certified": 1,"xmp_id": 3243042, "certified":
1,"xmp_id": 3243043, "certified": 1,"xmp_id": 3243044, "certified":
1,"xmp_id": 3243045, "certified": 1,"xmp_id": 3243046, "certified":
1,"xmp_id": 3243047, "certified": 1,"xmp_id": 3243048, "certified":
1,"xmp_id": 3243049, "certified": 1,"xmp_id": 3243050, "certified":
1,"xmp_id": 3243051, "certified": 1,"xmp_id": 3243052, "certified": 1,
在VB.Net中,我会使用类似这样的方法来获取每个“xmp_id”的值:
Dim inputString As String=RichTextBox1.Text
Dim模式为字符串=”(?Swift没有自己的正则表达式支持,但您可以使用Foundation的NSRegularExpression
类。它生成NSTextCheckingResult
对象。将Swift的String
类型与NSRegularExpression
和NSTextCheckingResult
一起使用是一件痛苦的事,因此请先将您的将字符串放入NSString
let text = "\"xmp_id\": 3243041, \"certified\": 1,\"xmp_id\": 3243042, \"certified\": 1,\"xmp_id\": 3243043, \"certified\": 1,\"xmp_id\": 3243044, \"certified\": 1,\"xmp_id\": 3243045, \"certified\": 1,\"xmp_id\": 3243046, \"certified\": 1,\"xmp_id\": 3243047, \"certified\": 1,\"xmp_id\": 3243048, \"certified\": 1,\"xmp_id\": 3243049, \"certified\": 1,\"xmp_id\": 3243050, \"certified\": 1,\"xmp_id\": 3243051, \"certified\": 1,\"xmp_id\": 3243052, \"certified\": 1," as NSString
let rx = NSRegularExpression(pattern: "\"xmp_id\": ([0-9]+)", options: nil, error: nil)!
let range = NSMakeRange(0, text.length)
let matches = rx.matchesInString(text, options: nil, range: range)
for matchObject in matches {
let match = matchObject as NSTextCheckingResult
let range = match.rangeAtIndex(1)
let value = text.substringWithRange(range)
println(value)
}
我精简了这个(?我如何循环这个来获取所有出现的情况?我还将检查这个,看看它是否至少找到了一个
let text = "\"xmp_id\": 3243041, \"certified\": 1,\"xmp_id\": 3243042, \"certified\": 1,\"xmp_id\": 3243043, \"certified\": 1,\"xmp_id\": 3243044, \"certified\": 1,\"xmp_id\": 3243045, \"certified\": 1,\"xmp_id\": 3243046, \"certified\": 1,\"xmp_id\": 3243047, \"certified\": 1,\"xmp_id\": 3243048, \"certified\": 1,\"xmp_id\": 3243049, \"certified\": 1,\"xmp_id\": 3243050, \"certified\": 1,\"xmp_id\": 3243051, \"certified\": 1,\"xmp_id\": 3243052, \"certified\": 1," as NSString
let rx = NSRegularExpression(pattern: "\"xmp_id\": ([0-9]+)", options: nil, error: nil)!
let range = NSMakeRange(0, text.length)
let matches = rx.matchesInString(text, options: nil, range: range)
for matchObject in matches {
let match = matchObject as NSTextCheckingResult
let range = match.rangeAtIndex(1)
let value = text.substringWithRange(range)
println(value)
}