Java Regex az, AZ, 0-9 and (.) (_) (-)

Writing a simple regex, but I've never been so good at it.

What I'm trying to do is check the string (file name) to make sure it contains only az, AZ, 0-9 or special underscores (_) for period (.) Or dash (-).

That's what i

if(filename.length() < 1 || !filename.matches("^[a-zA-Z0-9[.][_][-]]+"))
   return false;
else
   return true;

It seems to work, but for me it does not look very elegant. Is there a better / more readable way to write this?

Thanks in advance! Just try to learn how to write these finders better.

-Will be

+5
source share
3 answers

You do not need to use []inside a character class.

So you can write:

^[-a-zA-Z0-9._]+

Alternatively, you can use \\winstead a-zA-Z0-9_.

, :

^[-\\w.]+

, StackOverflow 22.10$$2011, StackOverflow 22.10. , , $ - :

^[-\\w.]+$
+10
try {
    boolean foundMatch = subjectString.matches("^[\\w.-]+$");
} catch (PatternSyntaxException ex) {
    // Syntax error in the regular expression
}

.

\w [a-zA-Z_0-9], , .

+1

, ( ), -.

, . , . , , , , .

Now it violates the general rule (using exceptions to determine the program flow) and has the disadvantage of switching to disk. But this is a different approach and may give you ideas that you can use.

public boolean isValidFileName(final String fileName) {
    final File file = new File(fileName);
    final boolean isValid = true;
    try {
        if (file.createNewFile()) {
            file.delete();
        }
    } catch (IOException e) {
        isValid = false;
    }
    return isValid;
}
0
source

All Articles