Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Regular Expression to match parentheses

I am trying to use regex to search through a string: "K1B92 (D) [56.094]" and I want to grab the "(D)" including the parentheses surrounding the "D". I am having trouble finding the correct expression to match the actual parentheses as simply putting parentheses will take it as a block and trying to escape the parentheses with "\" making it think its an expression to be evaluated. I also tried escaping "\(" with "\\(" as so: "\\([ABCD])\\)" but without luck. This is the code I have been using:

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 direct me towards the correct expression please? Thank you very much.

like image 374
joanna cheung Avatar asked Dec 19 '22 01:12

joanna cheung


2 Answers

The \\([ABCD])\\) part is OK, Correction: As @vacawama correctly said in his answer, the parentheses do not match here. \\([ABCD]\\) matches one of the letters A-D enclosed in parentheses.

The other problem is that there is no word boundary (\b pattern) between a space and a parenthesis.

So you could either (depending on your needs), just remove the \b patterns, or replace them by \s for white space:

let regex = NSRegularExpression(pattern: "\\s\\([ABCD]\\)\\s", ...

But since the matched string should not include the space you need a capture group:

let regex = NSRegularExpression(pattern: "\\s(\\([ABCD]\\))\\s", ...
// ...
let strRange = match?.rangeAtIndex(1)
like image 158
Martin R Avatar answered Dec 29 '22 00:12

Martin R


The regular expression you need is "\\([ABCD]\\)". You need the double escape \\ before both open paren ( and close paren ).

like image 36
vacawama Avatar answered Dec 28 '22 23:12

vacawama