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.
The
Correction: As @vacawama correctly said in his answer, the parentheses
do not match here. \\([ABCD])\\)
part is OK,\\([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)
The regular expression you need is "\\([ABCD]\\)"
. You need the double escape \\
before both open paren (
and close paren )
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With