Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use non-capturing groups in grep?

Tags:

grep

pcre

This answer suggests that grep -P supports the (?:pattern) syntax, but it doesn't seem to work for me (the group is still captured and displayed as part of the match). Am I missing something?

I am trying grep -oP "(?:syntaxHighlighterConfig\.)[a-zA-Z]+Color" SyntaxHighlighter.js on this code, and expect the results to be:

wikilinkColor externalLinkColor parameterColor ... 

but instead I get:

syntaxHighlighterConfig.wikilinkColor syntaxHighlighterConfig.externalLinkColor syntaxHighlighterConfig.parameterColor ... 
like image 211
waldyrious Avatar asked Feb 28 '13 13:02

waldyrious


People also ask

What is the use of non capturing group in regex?

Although they don't save the matched character sequence, non-capturing groups can alter pattern matching modifiers within the group. Some non-capturing groups can even discard backtracking information after a successful sub-pattern match.

What is capturing group in regex Javascript?

Groups group multiple patterns as a whole, and capturing groups provide extra submatch information when using a regular expression pattern to match against a string. Backreferences refer to a previously captured group in the same regular expression.


1 Answers

"Non-capturing" doesn't mean that the group isn't part of the match; it means that the group's value isn't saved for use in back-references. What you are looking for is a look-behind zero-width assertion:

grep -Po "(?<=syntaxHighlighterConfig\.)[a-zA-Z]+Color" file 
like image 158
Kent Avatar answered Sep 23 '22 17:09

Kent