Search code examples
regexpcre

Regex : Want to eliminate dash start case


I have below conditions.

  • It will search the term "page"
  • It catches String page - with quotes
  • It catches variable assignment like - int page=1
  • It will not catch the Strings with dash - "page-context", "previous-page"

So I got sample like ...

int page = 1
int page=1
import common.abc.page.PageSize;
import common.abc.page.*;
document.aForm.page=1;
map.put("page", 1);
response.write("<a href=\"page=1\">");
pageContent
class="page-context"
class="empty-page"
<%@ page
<%@ jsp:include page
scope="page"
someObject.page();
int pageSize =  7;

And here is what I made to pursue the goal. /\b(?!-)(page)(?!-)\b/mg.

I works nice without one case - the one has dash right before the page. empty-page should not match with regex. (Line 8,9,10 and the last should not matched)

How can I fix it? Thanks.


Solution

  • You may use this regex with a lookahead and lookbehind assertion:

    (?<!-)\bpage\b(?!-)
    

    RegEx Demo

    RegEx Details:

    • (?<!-): Negative lookbehind to fail the match if we have - at left hand side of current position
    • \bpage\b: Match exact word page (\b is for word boundary)
    • (?!-): Negative lookahead to fail the match if we have - at right hand side of current position