Search code examples
regexunixregex-negationregex-lookaroundsregex-greedy

regex to do multi line search in eclipse


I need a regular expression to match only the comment before the line containing "private final VARIABLE".

INPUT:

/**
*okay1
*/
menu
/**
*  okay2.
*/
private final VARIABLE;

OUTPUT should be :

/**
*  okay2.
*/
private final VARIABLE;

The strings okay1 and okay2 could be anything. They represent comments here. I tried doing this which does not work.

 ((\/\*\*[\S\s]*\*\/){1})[\s]*(private\s*final\s*VARIABLE\;)

This matches the first comment as well (okay1) which I dont want. I am familiar with regex but this is something not straightforward. Would appreciate any help. Thanks.


Solution

  • You may use a regex like

    /\*+[^*]*\*+(?:[^/*][^*]*\*+)*/\s*(private\s+final\s+VARIABLE;)
    

    See the online demo

    Details

    • /\*+ - match the comment start, /* and any 0+ asterisks after it
    • [^*]*\*+ - match 0+ characters other than * followed with 1+ literal *
    • (?:[^/*][^*]*\*+)* - 0+ sequences of:
      • [^/*][^*]*\*+ - not a / or * (matched with [^/*]) followed with 0+ non-asterisk characters ([^*]*) followed with 1+ asterisks (\*+)
    • / - closing /
    • \s* - 0+ whitespaces
    • (private\s+final\s+VARIABLE;) - Group 1: private, 1+ whitespaces, final, 1+ whitespaces, VARIABLE;.