Reputation: 155
Basically i want to match filename with .json extension but not file that start with . and excluding list.json.
This is what i come out with (without java string escapes)
(?i)^([^\.][^list].+|list.+)\.json$
I had use an online regex tester, Regexplanet to try my regex http://fiddle.re/x9g86
Everything works fine with the regex tester, however when i tried it in Java. Everything that has the letter l,i,s,t will be excluded... which is very confusing for me.
Can anyone give me some clues?
Many thanks in advance.
Upvotes: 2
Views: 140
Reputation: 28687
You're using a character exclusion class, [^list]
, which ignores character order and instead of excluding list
, excludes any cases of l
, i
, s
, or t
.
Instead, you want to use a negative lookahead:
(?i)(?!^list\.json$)[^\.].*\.json
Upvotes: 1
Reputation: 55609
A negative look-ahead will do it.
(?i)(?!\.|list\.json$).*\.json
(?!\.|list\.json$)
is a negative look-ahead checking that the characters following is not either list.json
followed by the end of the string, or .
.
Code:
String regex = "(?i)(?!\\.|list\\.json$).*\\.json";
System.out.println("list.json".matches(regex)); // false
System.out.println(".json".matches(regex)); // false
System.out.println("a.Json".matches(regex)); // true
System.out.println("abc.json".matches(regex)); // true
But NPE's more readable solution is probably preferred.
Upvotes: 1
Reputation: 500357
I want to match filename with
.json
extension but not file that start with.
and excludinglist.json
.
I am not sure you need regular expressions for this. I find the following much easier on the eye:
boolean match = s.endsWith(".json") && !s.startsWith(".") && !s.equals("list.json");
Upvotes: 8