3
votes

I need a regex to perform search in eclipse to match all strings that start with ${ and end with } but should not have pageContext between the two. For Example

${requestScope.user}

${sessionScope.user}

should match

but ${pageContext.request} should not

After all efforts I have made this regex (\${) which matches strings starting with ${ but some how doesn't meet my requirement.any help will be appreciated.

2

2 Answers

2
votes

You may use a negative lookahead to exclude specific matches:

\$\{(?!pageContext\.).*?\}
    ^^^^^^^^^^^^^^^^

The (?!pageContext\.) lookahead will fail all matches where { is followed with pageContext.. Also, you can use [^{}]* instead of .*?.

See the regex demo

Pattern details:

  • \$ - a literal $
  • \{ - a literal {
  • (?!pageContext\.) - fail the match if a pageContext. follows the { immediately
  • .*? - any 0+ characters other than a newline (or [^{}]* - zero or more characters other than { and })
  • \} - a literal }.

NOTE:

If you need to avoid matching any ${...} substring with pageContext. anywhere inside it, use

\$\{(?![^{}]*pageContext\.)[^{}]*\}
    ^^^^^^^^^  

Here, the [^{}]* inside the lookahead will look for pageContext. after any 0+ chars other than { and }.

0
votes

Look aheads or look behinds are expensive. You should prefer the optional match trick:

\$\{(?:.*pageContext.*|(.*))\}

Live Example

To avoid confusion let me specify that this will match any string with a "${" prefix and a "}" suffix, but if that string contained "pageContext" the 1st capture will be empty. If the 1st capture is non-empty you have a string matching your criteria.