Eric B.
Eric B.

Reputation: 24411

Cannot get Negative Lookahead regexp to properly match

I'm trying to match strings that do not have .jsp/.jspx extensions in Java and am having a lot of difficult with the negative lookahead pattern.

Given a bunch of strings:

String string1 = "templateName";
String string2 = "some/path"
String string3 = "basic/filename/no/extension"
String string4 = "some/path/to/file.jsp"
String string5 = "alternative/path/to/file.jspx"

I'm trying to find a regex that matches the first 3 and not the last 2.

I would have thought a regex with a negative lookahead would work.

Ex:

Pattern p = new Pattern.compile( "(.+)(?!\\.jsp[x]?)")

But that pattern seems to match all the above strings. I initially thought that group 1 might be too greedy, so I've tried (.+?), but that does not help either.

This SO Post does a very good job of explain the negative lookahead, but it isn't helping me unfortunately find the right combination.

Am I missing something obvious?

Upvotes: 0

Views: 1634

Answers (2)

Indu Devanath
Indu Devanath

Reputation: 2188

Here's another negative lookbehind:

Pattern p = new Pattern.compile(".*(?<!.jspx?)$");

(?<!.jspx?) is a negated lookbehind assertion, which means that before the end of the string, there is no .jsp or .jspx

You are looking behind the end of string $

Reference:

http://www.regular-expressions.info/lookaround.html

Regex not ending with

Upvotes: 1

anubhava
anubhava

Reputation: 785226

You can use negative lookbehind as:

Pattern p = new Pattern.compile( "^(.+)(?<!\\.jspx?)$" );

OR you can use negative lookahead as:

Pattern p = new Pattern.compile( "^(?!.+?\\.jspx?$)(.+)$" );

Upvotes: 2

Related Questions