56

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
...
3
  • Can you show some sampel input/output ? Feb 28, 2013 at 13:10
  • 1
    @sputnick I edited the question to add more details.
    – waldyrious
    Feb 28, 2013 at 13:16
  • you should've included the contents of the file that you're grepping, before showing what you expect or what you get
    – barlop
    Apr 11, 2016 at 10:49

1 Answer 1

84

"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
8
  • Note that all lookbehinds are zero width
    – barlop
    Apr 11, 2016 at 10:47
  • 9
    Lookbehinds need to be fixed length. In this case it helps, but it doesn't in others.
    – Cromax
    Jul 17, 2016 at 20:12
  • 28
    For references, (?<=…) is positive lookbehind assertion, (?<!…) is negative lookbehind assertion, (?=…) is positive lookahead assertion, and (?!…) is negative lookahead assertion. More here.
    – Rockallite
    Feb 8, 2017 at 7:11
  • 7
    Is there any variant of this that would handle variable width? E.g. if instead of the dot, I had an unknown number of spaces at the end of the lookbehind and wanted to do grep -Po "(?<=syntaxHighlighterConfig +)[a-zA-Z]+Color" file. Right now I get the complaint grep: lookbehind assertion is not fixed length. Thanks.
    – SSilk
    May 30, 2017 at 18:01
  • 2
    You could use \K as a variable length negative lookbehind... Keep the stuff left of \K.
    – Ray Foss
    Sep 11, 2020 at 3:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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