Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex allowing a space character in Java

Tags:

java

regex

Hey all, so I'm trying to allow some text input which goes through a regex check before it's sent off. I want the text to only include A-Z, 0-9, and the space " " character. Here is my code now:

if(!title.matches("[a-zA-Z0-9_]+") {
    //fail
}
else {
    //success
}

However this still gives the //fail result when I input something like "This is a test"

Any ideas? Thanks all.

like image 933
JMRboosties Avatar asked Apr 08 '11 23:04

JMRboosties


2 Answers

You're not including the space in the Regex. Try the following:

if (!title.matches("[a-zA-Z0-9 ]+"))
like image 121
Jason McCreary Avatar answered Sep 18 '22 23:09

Jason McCreary


\s allows for any ASCII whitespace character. Consider using that rather than " ".

if(!title.matches("[a-zA-Z0-9_\s]+")) {
    //fail
}
else {
    //success
}
like image 21
Scott Nguyen Avatar answered Sep 18 '22 23:09

Scott Nguyen