Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

ios - 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.

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{
         }
      }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

Swift 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.

Swift 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. That's why I casted query into an NSString


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...