skip to Main Content

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


  1. 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:

    let output = input.matchesFor(regularExpression: try .init(pattern: "\{(.*?)\}"))
        .map { $0.replacingOccurrences(of: "{", with: "").replacingOccurrences(of: "}", with: "") }
    
    print(output)
    
    //["un:23456", "un:654, Bartek"]
    

    Updated as @Larme suggested:

    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(at: 1)) } //<- here
    }
    
    let output = input.matchesFor(regularExpression: try .init(pattern: "\{(.*?)\}"))
    
    print(output)
    
    //["un:23456", "un:654, Bartek"]
    
    Login or Signup to reply.
  2. I would use a character class to terminate the match at the first }. [^}] means "match anything except }"

    /{([^}]*)}/
    

    https://regex101.com/r/t9eLmP/1

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search