Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

Regex Java allow number, letters, special char (some)

I have a file name, lets say upload 23_3.jpg. I would like to allow only letters, (.) period, (-) hypen sign, underscore (_)

Pattern p = Pattern.compile("[^a-z0-9_.]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(i.getFileName());

boolean specialCharFound = m.find(); //this will return true if any other characters are found

^ means not a-z, letters and I added _ and ., but it doesn't work. Any idea how to add '_' '.' '-' characters?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use Pattern.compile("[\w\s.-]+") and m.matches():

Pattern p = Pattern.compile("[\w\s.-]+");
Matcher m = p.matcher(i.getFileName());
boolean isValid = m.matches();

See regex proof.

Explanation

[ws.-]+                any character of: word characters (a-z, A-
                           Z, 0-9, _), whitespace (
, 
, , f,
                           and " "), '.', '-' (1 or more times
                           (matching the most amount possible))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...