-4

I have a sentence which starts and ends with '_h'. I want to generate a regex which can catch multiple occurences of this case in a complete string.

I have generated a regex that looks like this "_h.[a-zA-Z0-9]._h". I want to add a "global flag" like the one in JavaScript but wasn't able to find any solution for it.

Input String: "_h Hello _h _h World _h"
Current output: Hello World

Expected output: [Hello, World]
Cristik
  • 30,989
  • 25
  • 91
  • 127
CoderSulemani
  • 123
  • 11
  • What have you tried so far? Can you share some of your attempts, to help us better understand the problem you're facing? – Cristik Feb 03 '19 at 08:20
  • Try it like this using a capturing group `_h\s*([a-zA-Z0-9]+)\s*_h` or using lookarounds `(?<=_h\s)[a-zA-Z0-9]+(?= _h)` – The fourth bird Feb 03 '19 at 08:52

1 Answers1

0

You could do something like this :

let str = "_h Hello _h _h World _h"

let range =  NSRange(str.startIndex..., in: str)

let regex = try! NSRegularExpression(pattern: "(?<=_h).+?(?=_h)")

let matches = regex.matches(in: str, range: range)

let results: [String] = matches.compactMap { match in
    let subStr = String(str[Range(match.range, in: str)!]).trimmingCharacters(in: .whitespacesAndNewlines)
    return subStr.isEmpty ? nil : subStr
}

print(results)  //["Hello", "World"]

Here is the regex explained :

  • (?<=_h) : Positive lookbehind for _h literally (case sensitive);
  • .+? : Matches any character (except for line terminators), between 1 and unlimited times, as few times as possible, expanding as needed;
  • (?=_h) : Positive lookahead for _h literally (case sensitive).

N.B : Force-unwrapping when constructing subStr is safe.

ielyamani
  • 17,807
  • 10
  • 55
  • 90