You can't use patterns of unknown length in lookbehind patterns with ICU regular expressions. Your pattern contains .*
in the lookbehind, so it is an invalid ICU regexp (see the length of possible strings matched by the look-behind pattern must not be unbounded (no *
or +
operators.) ICU lookbehind documentation part).
There are two ways:
- Replace
.*
with .{0,x}
where x
is the max number of chars you expect to separate the left-hand pattern from the right-hand pattern, ICU regex lookbehinds allow the limiting (or interval, range) quantifier, that is why they are also called "constrained-width")
- Re-vamp your pattern to use a consuming pattern instead of lookarounds, wrap the part you need to extract with capturing parentheses and modify your code to grab Group 1 value.
Here is Approach 2, which is recommended:
let str = "pod 'Alamofire', :git => 'https://github.com/Alamofire/Alamofire.git', :branch => 'dev'"
let rng = NSRange(location: 0, length: str.utf16.count)
let regex = try! NSRegularExpression(pattern: "'Alamofire'.*:git\\s*=>\\s*'([^']+)'")
let matches = regex.matches(in: str, options: [], range: rng)
let group1 = String(str[Range(matches[0].range(at: 1), in: str)!])
print(group1) // => https://github.com/Alamofire/Alamofire.git
See the regex demo, the green highlighted substring is the value you get in Group 1.
Pattern details:
'Alamofire'
- a literal string
.*
- any 0+ chars other than line break chars, as many as possible (replace with .*?
to match as few as possible)
:git
- a literal substring
\s*=>\s*
- a =>
substring wrapped with 0+ whitespaces
'([^']+)'
- '
, then a capturing group #1 matching 1+ chars other than '
and then a '
char.