在Java中,可以使用正则表达式来检查一个字符串是否只包含字母、数字、空格和短划线。以下是一个示例代码:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main {
public static void main(String[] args) {
String input = "This-is a string 123";
String regex = "^[a-zA-Z0-9\\s-]+$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
System.out.println("The input string only contains alphanumeric characters, spaces, and hyphens.");
} else {
System.out.println("The input string contains invalid characters.");
}
}
}
在这个示例中,我们使用了正则表达式 ^[a-zA-Z0-9\\s-]+$
来匹配字符串。这个正则表达式的意思是:
^
表示字符串的开头[a-zA-Z0-9\\s-]
表示允许的字符集,包括大小写字母、数字、空格和短划线+
表示允许一个或多个这样的字符$
表示字符串的结尾如果输入字符串符合这个正则表达式,那么它只包含字母、数字、空格和短划线。否则,它包含了一些其他的字符。
在这个示例中,我们使用了 Pattern
和 Matcher
类来执行正则表达式匹配。如果匹配成功,我们输出一条消息表示输入字符串符合要求,否则输出另一条消息表示输入字符串不符合要求。
领取专属 10元无门槛券
手把手带您无忧上云