检查字符串是否没有字母

Har*_*ini 2 java regex

我正在尝试查找字符串是否仅包含数字和特殊字符。

我尝试了下面的代码,但没有用

String text="123$%$443";
String regex = "[0-9]+";
String splChrs = "-/@#$%^&_+=()" ;
if ((text.matches(regex)) && (text.matches("[" + splChrs + "]+"))) {
  System.out.println("no alphabets");
}
Run Code Online (Sandbox Code Playgroud)

use*_*900 8

仅排除使用^字母:

[^a-zA-Z]+
Run Code Online (Sandbox Code Playgroud)

观看演示


小智 6

如果要检查text 不包含任何字母[A-Za-z],请尝试以下操作:

if (!text.matches("[A-Za-z]+")) {
  System.out.println("no letters");
}
Run Code Online (Sandbox Code Playgroud)

如果你想检查text 只包含数字和给定的特殊字符,试试这个:

String regex = "[0-9\\-/@#$%^&_+=()]+";
if (text.matches(regex)) {
  System.out.println("no letters");
}
Run Code Online (Sandbox Code Playgroud)

请注意,-必须由 a\转义,而 a本身必须被转义。