The negative lookahead ^(?!\.).+$
does work. Here it is in Java:
String[] files = {
".afile",
".anotherfile",
"bfile.file",
"bnotherfile.file",
".afolder/",
".anotherfolder/",
"bfolder/",
"bnotherfolder/",
"",
};
for (String file : files) {
System.out.printf("%-18s %6b%6b%n", file,
file.matches("^(?!\\.).+$"),
!file.startsWith(".")
);
}
The output is (as seen on ideone.com):
.afile false false
.anotherfile false false
bfile.file true true
bnotherfile.file true true
.afolder/ false false
.anotherfolder/ false false
bfolder/ true true
bnotherfolder/ true true
false true
Note also the use of the non-regex String.startsWith
. Arguably this is the best, most readable solution, because regex is not needed anyway, and startsWith
is O(1)
where as the regex (at least in Java) is O(N)
.
Note the disagreement on the blank string. If this is a possible input, and you want this to return false
, you can write something like this:
!file.isEmpty() && !file.startsWith(".")
See also
.
must be escaped as\.
. See my answer below. – Withdrawn