简体   繁体   English

正则表达式获取两个%字符之间的字符串

[英]regex to get string between two % characters

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. 现在使用以下正则表达式,有人可以帮助获得确切的Regax格式。

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: 试试这个:

Swift 4 斯威夫特4

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 uses UTF-16 encoding so NSMakeRange is called with the number of UTF-16 code units. NSString使用UTF-16编码,因此使用UTF-16代码单元的数量调用NSMakeRange

Swift 2 斯威夫特2

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"]

Getting a substring out of Swift's native String type is somewhat of a hassle. 从Swift的原生String类型中获取子String有点麻烦。 That's why I casted query into an NSString 这就是我将query转换为NSString

I have written a method for regular express. 我写了一个常规快递的方法。 Your regex is fine. 你的正则表达没问题。 You can test your regexes here . 你可以在这里测试你的正则表达式。 The method is: 方法是:

 func regexInText(regex: String!, text: String!) -> [String] {

        do {
            let regex = try NSRegularExpression(pattern: regex, options: [])
            let nsString = text as NSString
            let results = regex.matchesInString(text,
                options: [], range: NSMakeRange(0, nsString.length))
            return results.map { nsString.substringWithRange($0.range)}
        } catch let error as NSError {
            print("invalid regex: \(error.localizedDescription)")
            return []
        }
    }

You can call it whereever you want. 您可以随意调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM