This question already has an answer here:

Hi I've created a regex which I need to run with grep, I'm pretty sure the regex is fine as it works with online regex tools, however when I run

grep -r -P -o -h '(?<=(?<!def )my_method )(["'])(?:(?=(\\?))\2.)*?\1'

I get the error Syntax error: ")" unexpected, I'm not really sure what the problem is, any help would be great.

share|improve this question

marked as duplicate by don_crissti, Eric Renouf, Sato Katsura, GAD3R, roaima yesterday

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

Your regular expression is quoted with single quotes, but it also contains a single quote.

The single quote in ["'] needs to be escaped, or it will signal the end of the quoted string to the shell.

This will fix it:

grep -r -P -o -h '(?<=(?<!def )my_method )(["'\''])(?:(?=(\\?))\2.)*?\1'
#                                            ^^^^

With ["'\''], the first ' ends the first part of the string, the \' inserts a literal single quote, and the last ' starts a new single quoted string that will be concatenated with the previous bits. Only the middle single quote will end up in the regular expression itself, the other two will be removed by the shell.

share|improve this answer
3  
Nice Tricky method. Alternative : (["\x27]) will work fine (replacing the single quote with it's ascii code) – George Vasiliou yesterday
    
@GeorgeVasiliou That's also a good solution, yes. \x27 is as many characters as '\''. – Kusalananda yesterday
1  
Though '\'' is transferable to other non-regex situations whereas \x27 is not. – Muzer yesterday

As @Kusalananda explained, the problem is the ' inside the regex. A simple solution is to use " for the regex since " can be escaped even inside a "-quoted string, unlike ' which cannot be escaped inside a '-quoted string:

grep -rPoh "(?<=(?<!def )my_method )([\"'])(?:(?=(\\?))\2.)*?\1"
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.