Here is my input string:
let input = "Hello, {un:23456} is under investigation {un:654, Bartek} along with Jason."
and simple extension:
extension String {
func matchesFor(regularExpression: NSRegularExpression) -> [String] {
let nsstring = self as NSString
let matches = regularExpression.matches(in: self, range: NSRange(location: 0, length: nsstring.length))
return matches.map { nsstring.substring(with: $0.range) }
}
}
and the output is:
["{un:23456} is under investigation {un:654, Bartek}"]
instead of:
["{un:23456}", "{un:654, Bartek}"]
Why?
My regex is "\{un:(:?[0-9]{1,9}).*\}"
2
Answers
Change
.*
->.*?
. The?
stop*
being greedy, match the string that ends with}
and no more.Or, get all between
{ }
:As you said in your comment, you also need to remove these curly braces:
Updated as @Larme suggested:
I would use a character class to terminate the match at the first
}
.[^}]
means "match anything except}
"https://regex101.com/r/t9eLmP/1