简体   繁体   中英

regex for matching strings that have illegal filename characters

I been trying to figure out how this blasted regex for two hours!!! It's midnight I gotta figure this out and go to bed!!!

String str = new String("filename\\");
if(str.matches(".*[?/<>|*:\"{\\}].*")) {
    System.out.println("match");
}else {
    System.out.println("no match");
}

".*[?/<>|*:\\"{\\\\}].*" is my regex expression. It catches everything correctly except the backslash!!! I need to know how to make it catch the backslash correctly please help!

FYI, the illegal characters i'm trying to catch are ? \\ / < > | * : " I've got it working exception for the backslash

The problem is that \\\\ escapes a backslash in a Java String and you have to escape it in the regex. That means using four backslashes:

if ("ab\\d".matches("[abd\\\\]*") {
  // match
}

Because two of the backslashes are Java String escapes the regex is really:

[abc\\]*

and \\\\ is required in the regex to escape the backslash.

I know this is a fairly old question at this point but I found it while working on the same issue and I figured future readers might find this useful:

In addition to catching invalid characters in a filename there are a few other things to take into account. Filenames cannot begin or end with a space, they cannot end with a . character, and they cannot be an empty string. This regular expression might be a little bit more thorough for matching a bad filename:

^(\s+.*|.*[\\/:\"?*|<>].*|.*\s+||.*\.)$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM