Home > database >  NSRegularExpression (.*) any single character zero or more times doesn't work
NSRegularExpression (.*) any single character zero or more times doesn't work

Time:11-30

My regex which will be used for code liniting purpose should find a function definitions which have first line empty.

Here is my string:

let text = """
    override func withFirstLineEmpty(_ animated: Bool) {

        print()
    }
    
    override func withNoFirstLineEmpty(_ animated: Bool) {
        print()
    }
"""

This is my regex which was tested with regex101 website: func.*{\n\n

This is my code:

let regexString = "func.*{\n\n"
let regexEscaped = NSRegularExpression.escapedPattern(for: regexString)
let regex = try! NSRegularExpression(pattern: regexEscaped, options: [.useUnixLineSeparators, .dotMatchesLineSeparators])
let matches = regex.matches(in: text, options: [], range: NSRange(text)!)

matches array of results is empty.

Is this a problem of my regex or NSRegularExpression configuration?

CodePudding user response:

It's highly recommended to search for \s which includes both \n and \r

And basically the NSRange is wrong. You have to use the dedicated initializer NSRange(_:in:). And the escapedPattern line is actually not needed. There is a native Swift syntax. On the other hand the { must be escaped.

let text = """
    override func withFirstLineEmpty(_ animated: Bool) {

        print()
    }
    
    override func withFirstLineEmpty(_ animated: Bool) {
        print()
    }
"""

let regexString = #"func.*\{\s{2}"#
let regex = try! NSRegularExpression(pattern: regexString)
let matches = regex.matches(in: text, range: NSRange(text.startIndex..., in: text))
  • Related