Adeline Adeline - 4 months ago 25
Swift Question

Building Swift / ObjC regular expression

In a text string, I am trying to fetch everything between

[DATA FORMAT]
and
/DATA FORMAT]


and

Columns Format:
and
/DATA FORMAT]


to this goal I use regular expressions.

While the pattern

"\\[DATA FORMAT\\](.*?)\\[/DATA FORMAT\\]"


works as expected, the pattern

"Columns Format(*.?)\\[/DATA FORMAT\\]"


gives an error

Optional("The value “Columns Format(*.?)\\[/DATA FORMAT\\]” is invalid.")

The value “Columns Format(*.?)\[/DATA FORMAT\]” is invalid.


printed in the console (first line: localizedFailureReason, second line:localizedDescription)

What did I miss ?

Code :

extension String
{
func match (pattern: String,
options: RegularExpression.Options = [.caseInsensitive, .dotMatchesLineSeparators]) -> [String]
{
do
{
let regex = try RegularExpression(pattern: pattern, options: options)
let regexAnsw = regex.matches(in: self, options: RegularExpression.MatchingOptions.withTransparentBounds, range: NSMakeRange(0, self.characters.count))

var retStrings = [String]()

for rs in regexAnsw
{
if let range = self.range(from: rs.range)
{
retStrings.append(self.substring(with: range))
}
else
{
print("match: cant' convert NSRange to range")
}
}

return retStrings
}
catch let error as NSError
{
print(error.localizedFailureReason)
print(error.localizedDescription)

return [String]()
}
}
}

Answer

You have your * and . swapped in the second regex (in the capture group right after "Column Format"). This makes the regex invalid; the * isn't referring to anything.

Comments