正则表达式允许Java中的空格字符

时间:2023-02-12 20:13:42

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:

嘿所有,所以我试图允许一些文本输入,在它被发送之前通过正则表达式检查。我希望文本只包含A-Z,0-9和空格“”字符。这是我的代码:

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.

有任何想法吗?谢谢大家。

2 个解决方案

#1


20  

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

您没有在正则表达式中包含空格。请尝试以下方法:

if (!title.matches("[a-zA-Z0-9 ]+"))

#2


3  

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

\ s允许任何ASCII空白字符。考虑使用它而不是“”。

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

#1


20  

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

您没有在正则表达式中包含空格。请尝试以下方法:

if (!title.matches("[a-zA-Z0-9 ]+"))

#2


3  

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

\ s允许任何ASCII空白字符。考虑使用它而不是“”。

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