5

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{
         }
      }
Madhu
  • 994
  • 1
  • 12
  • 33
  • Does this even compile?? `query` and `characters.count` and `matchesInString` are all non-optional and `regex` is unwrapped if the first optional binding succeeds. Apart from that you should **never** use `try!` in this particular context. – vadian Mar 14 '16 at 19:11

2 Answers2

24

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

Code Different
  • 90,614
  • 16
  • 144
  • 163
0

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.

ridvankucuk
  • 2,407
  • 1
  • 23
  • 41
  • Why are the parameter strings implicit unwrapped optionals? If you call the function with `regexInText(nil, text: nil)` the code will crash... – vadian Mar 14 '16 at 19:22