Skwiggs Skwiggs - 1 month ago 10
Swift Question

Regex - Match parentheses without matching their contents

I just need to match parentheses around some content that has to match specific criteria. I need to match only the parentheses so that I can then do a quick replacement of only those parentheses and keep their content.

For the moment, what I have matches those specific parentheses, but unfortunately also their contents:



The criteria for matching parentheses are as following:


  • only match parentheses that contain
    \d{2,7}



I have tried positive lookahead (
\((?=\d{2,7})\)
), and while it does indeed not consume whatever follows the open parenthesis, it then fails to match the closing parenthesis as it backtracks to before the content...

So yeah, any help would be appreciated :)

Answer

Pure RegEx pattern: \((?=\d{2,7}\))|(?<=\()\d{2,7}\K\)


Update: I don't know about Swift, but according to this documentation, Template Matching Format part, $n can also be used similarly, as in

let myString = "(32) 123-323-2323"
let regex = try! NSRegularExpression(pattern: "\\((\\d{2,7})\\)")
let range = NSMakeRange(0, myString.characters.count)
regex.stringByReplacingMatchesInString(myString,
                                       options: [],
                                       range: range,
                                       withTemplate: "$1")

With the assumption that you are using Java, I would suggest something as simple as str.replaceAll("\\((\\d{2,7})\\)", "$1")

The pattern \((\d{2,7})\) captures the whole expression with parantheses with the number in group 1 and replaces it with only the number inside, thus effectively removing the surrounding brackets.

Comments