我正在试图弄清楚如何从更大的字符串中获取字符串的每次出现。
较大字符串的示例:
"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 pattern As String = "(?<=\<b1\>).+?(?=\<\/b1\>)"
Dim col As MatchCollection = Regex.Matches(inputString, pattern)
For Each match As Match In col
Console.WriteLine(match.Groups(1).Value)
Next
我到处搜索过,无法找到与VB.Net代码相同的内容。我想在“xmp_ID”:和,“认证”之间找到字符串:任何人都有任何想法如何在Swift中进行此操作?
答案 0 :(得分:1)
Swift没有自己的正则表达式支持,但您可以使用Foundation的NSRegularExpression
类。它会生成NSTextCheckingResult
个对象。使用带有String
和NSRegularExpression
的Swift 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)
}