Swift - regex to match parentheses
I am trying to use a regex to search on a string: "K1B92 (D) [56.094]"
and I want to capture "(D)"
including the parentheses associated with "D"
. I am having trouble finding the correct expression to match the actual parentheses, as simply placing the parentheses will accept it as a block and try to avoid the parentheses with "\"
, making it think that this expression should be evaluated. I also tried to escape "\("
with "\\("
like this: "\\([ABCD])\\)"
but no luck. This is the code I used:
let str = "K1B92 (D) [56.094]"
let regex = NSRegularExpression(pattern: "\\b\\([ABCD])\\)\\b", options: NSRegularExpressionOptions.CaseInsensitive, error: nil)
let match = regex?.firstMatchInString(str, options: NSMatchingOptions.WithoutAnchoringBounds, range: NSMakeRange(0, count(str)))
let strRange = match?.range
let start = strRange?.location
let length = strRange?.length
let subStr = str.substringWithRange(Range<String.Index>(start: advance(str.startIndex, start!), end: advance(str.startIndex, start! + length!)))
// "\\b\([ABCD])\)\\b" returns range only for the letter "D" without parentheses.
// "\\b\\([ABCD])\\)\\b" returns nil
Can you guide me to the correct expression, please? Thank you very much.
source to share
Part
Correction: As @vacawama correctly said in his answer, the parentheses don't match here. \\([ABCD])\\)
is okay,\\([ABCD]\\)
matches one of the letters AD enclosed in parentheses.
Another problem is that there is no \b
pattern boundary between space and parenthesis.
This way you can (depending on your needs) just remove the templates, \b
or replace them with \s
for spaces:
let regex = NSRegularExpression(pattern: "\\s\\([ABCD]\\)\\s", ...
But since the matched string should not contain the required space, the capturing group:
let regex = NSRegularExpression(pattern: "\\s(\\([ABCD]\\))\\s", ...
// ...
let strRange = match?.rangeAtIndex(1)
source to share