I'm playing with the following code in Swift to build an appropriate regex for an application:
let regExp = "-(\\([0-9.a-z()+-×÷√^₁₀²³/]+\\)|[0-9.a-z()+-×÷√^₁₀²³/]+)"
let testString = "-(hsjshdf) -hsghsgsgs -(k) -(1/64) -dhsg62 -(p)"
let regularExpression = try! NSRegularExpression(pattern: regExp, options: [])
let matchesArray = regularExpression.matches(in: testString, options: [], range: NSRange(location: 0, length: testString.characters.count))
for match in matchesArray {
for i in 0..<match.numberOfRanges {
let range = match.rangeAt(i)
let r = testString.index(testString.startIndex, offsetBy: range.location) ..< testString.index(testString.startIndex, offsetBy: range.location + range.length)
print(testString.substring(with: r))
}
}
The result I get is as follows:
-(hsjshdf)
(hsjshdf)
-hsghsgsgs
hsghsgsgs
-(k)
(k)
-(1/64)
(1/64)
-dhsg62
dhsg62
-(p)
(p)
However, I want the regexp match and group the substring within "()", so I can get the following output:
-(hsjshdf)
(hsjshdf)
hsjshdf
-hsghsgsgs
hsghsgsgs
-(k)
(k)
k
-(1/64)
(1/64)
1/64
-dhsg62
dhsg62
-(p)
(p)
p
I tried the following modification to the original regex, and it worked for the substring "-(hsjshdf)" but crashed when printing the matches of the substring "-hsghsgsgs" with an execution time error (fatal error: cannot increment beyond endIndex):
let regExp = "-(\\(([0-9.a-z()+-×÷√^₁₀²³/]+)\\)|[0-9.a-z()+-×÷√^₁₀²³/]+)"
I'm not familiar with NSRegularExpression. Am I using the wrong regexp? Do I need to set an special option?
Thanks for your help. Kindest regards.
/TB