Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping Parentheses in Regex

Tags:

regex

I have a regex which has optional anchors at the end e.g.

(\.|,|\/) 

I am trying to add ")" to this but if I escape it

(/.|,|\/|\)) 

it isn't found and if don't escape it is treated as part of the expression and fails since there is no open parens. How can I escape it so it is treated as a character and found?

like image 893
user3601725 Avatar asked May 14 '14 16:05

user3601725


People also ask

How do you escape parentheses in regex?

Since parentheses are also used for capturing and non-capturing groups, we have to escape the opening parenthesis with a backslash. An explanation of how literalRegex works: / — Opens or begins regex. \( — Escapes a single opening parenthesis literal.

What is escaping in regex?

The backslash in a regular expression precedes a literal character. You also escape certain letters that represent common character classes, such as \w for a word character or \s for a space.

Can you use parentheses in regex?

By placing part of a regular expression inside round brackets or parentheses, you can group that part of the regular expression together. This allows you to apply a quantifier to the entire group or to restrict alternation to part of the regex. Only parentheses can be used for grouping.

What is difference [] and () in regex?

This answer is not useful. Show activity on this post. [] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.


1 Answers

\) is the correct way for escaping a paranthesis. Make sure you are properly escaping the \(\\) in the string literal.

like image 100
Farhad Alizadeh Noori Avatar answered Oct 14 '22 06:10

Farhad Alizadeh Noori