正则表达式获取两个%字符之间的字符串 [英] regex to get string between two % characters

查看:100
本文介绍了正则表达式获取两个%字符之间的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要提取两个%"字符之间的字符串,查询字符串中可能出现多次. 现在正在使用以下正则表达式,有人可以帮助获取确切的Regax格式.

I need to extract string between two "%" characters, multiple occurrences can be present in the query string. now am using the following regex, can somebody help to get the exact Regax format.

let query =  "Hello %test% ho do you do %test1%"
let regex = try! NSRegularExpression(pattern:"%(.*?)%", options: [])

  if let results = regex?.matchesInString(query, options: .Anchored,  range: NSMakeRange(0,query.characters.count)){
    for match in results{
         }
      }

推荐答案

您的模式很好,但是您的代码未编译.尝试以下方法:

Your pattern is fine but your code didn't compile. Try this instead:

let query = "Hello %test% how do you do %test1%"
let regex = try! NSRegularExpression(pattern:"%(.*?)%", options: [])
var results = [String]()

regex.enumerateMatches(in: query, options: [], range: NSMakeRange(0, query.utf16.count)) { result, flags, stop in
    if let r = result?.range(at: 1), let range = Range(r, in: query) {
        results.append(String(query[range]))
    }
}

print(results) // ["test", "test1"]

NSString使用UTF-16编码,因此会使用UTF-16代码单元的数量来调用NSMakeRange.

NSString uses UTF-16 encoding so NSMakeRange is called with the number of UTF-16 code units.

let query = "Hello %test% how do you do %test1%"
let regex = try! NSRegularExpression(pattern:"%(.*?)%", options: [])
let tmp = query as NSString
var results = [String]()

regex.enumerateMatchesInString(query, options: [], range: NSMakeRange(0, tmp.length)) { result, flags, stop in
    if let range = result?.rangeAtIndex(1) {
        results.append(tmp.substringWithRange(range))
    }
}

print(results) // ["test", "test1"]

从Swift的本机String类型中获取子字符串有点麻烦.这就是为什么我将query强制转换为NSString

Getting a substring out of Swift's native String type is somewhat of a hassle. That's why I casted query into an NSString

这篇关于正则表达式获取两个%字符之间的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆