4

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.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
joanna cheung
  • 161
  • 3
  • 9

2 Answers2

7

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)
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • I did identify her parentheses issue, which was the original question, but your answer is the most complete. I up voted it and think it should be the accepted answer. (comment corrected for proper pronoun usage when referring to the OP) – vacawama Aug 02 '15 at 14:59
  • This solution worked perfectly. Thank you Martin R and Vacawama for answering if so promptly. Greatly appreciated – joanna cheung Aug 03 '15 at 07:44
5

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

vacawama
  • 150,663
  • 30
  • 266
  • 294