Regex to catch all files but those starting with "."
Asked Answered
P

4

7

In a directory with mixed content such as:

.afile
.anotherfile
bfile.file
bnotherfile.file
.afolder/
.anotherfolder/
bfolder/
bnotherfolder/

How would you catch everything but the files (not dirs) starting with .?
I have tried with a negative lookahead ^(?!\.).+? but it doesn't seem to work right.
Please note that I would like to avoid doing it by excluding the . by using [a-zA-Z< plus all other possible chars minus the dot >]

Any suggestions?

Petrick answered 25/5, 2010 at 22:14 Comment(0)
P
19

This should do it:

^[^.].*$

[^abc] will match anything that is not a, b or c

Planetarium answered 25/5, 2010 at 22:18 Comment(5)
This answer is incorrect because . must be escaped as \.. See my answer below.Withdrawn
I don't think the dot has special meaning with a bracket expression . . . the above works for me.Fennec
Indeed so it seems. Odd but ok.Withdrawn
The . does not need to be escaped inside a character class.Corriveau
Thanks for reminding me negative classes! Takes no time to get rusty with regex;) I was going through the mythical onigoruma doc and totally missed it (geocities.jp/kosako3/oniguruma/doc/RE.txt). Also great to know escaping is not needed in classes.Petrick
W
2

Escaping .and negating the characters that can start the name you have:

^[^\.].*$

Tested successfully with your test cases here.

Withdrawn answered 25/5, 2010 at 22:21 Comment(0)
E
1

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

Equi answered 26/5, 2010 at 11:3 Comment(0)
B
0

Uhm... how about a negative character class?

[^.]

to exclude the dot?

Boyse answered 25/5, 2010 at 22:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.