3.9. Matching Regex Syntax Characters

To match characters that are part of regular expression syntax, such as ( ) [ ] ^ $ | ? and /, that is to say, to capture them as text, you need to escape them. The escape character in regexes is the same as elsewhere in JavaScript, namely, the backslash. Earlier we gave an example of a regex that matched all text enclosed by sterling symbols, but a more realistic example would be to find text enclosed in parentheses. To do so, you need to escape the parentheses to tell the regex that you're interested in matching those round brackets, not in grouping anything:

myString = 'one (two) three (four) five six';
myString.match( /\(.*?\)/g );

But apart from the forward slash (which terminates a regex), escaping is not necessary in character classes. For instance, in the more efficient version of the regex that finds anything in parentheses using a negated character class the closing parenthesis within the square brackets is not escaped, outside the brackets, it is:

myString.match(/\([^)]+\)/g);

You could escape the parenthesis there, it's just not necessary. And as regexes with several escaped characters in them tend to become pretty unreadable, you're advised to use escapes only when you must.

Get Automating InDesign with Regular Expressions now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.