简体   繁体   English

如何检查字符串是否仅由字母和数字组成

[英]How to check if a string is made only of letters and numbers

Let's say a user inputs text.假设用户输入文本。 How does one check that the corresponding String is made up of only letters and numbers?如何检查相应的String是否仅由字母和数字组成?

import java.util.Scanner;
public class StringValidation {
    public static void main(String[] args) {
       Scanner in = new Scanner(System.in);
       System.out.println("Enter your password");
       String name = in.nextLine();
       (inert here)

You can call matches function on the string object.您可以在字符串对象上调用matches函数。 Something like就像是

str.matches("[a-zA-Z0-9]*")

This method will return true if the string only contains letters or numbers.如果字符串仅包含字母或数字,则此方法将返回 true。

Tutorial on String.matches: http://www.tutorialspoint.com/java/java_string_matches.htm String.matches 教程: http ://www.tutorialspoint.com/java/java_string_matches.htm

Regex tester and explanation: https://regex101.com/r/kM7sB7/1正则表达式测试器及说明: https : //regex101.com/r/kM7sB7/1

  1. Use regular expressions :使用正则表达式:

     Pattern pattern = Pattern.compile("\\\\p{Alnum}+"); Matcher matcher = pattern.matcher(name); if (!matcher.matches()) { // found invalid char }
  2. for loop and no regular expressions : for 循环,没有正则表达式:

     for (char c : name.toCharArray()) { if (!Character.isLetterOrDigit(c)) { // found invalid char break; } }

Both methods will match upper and lowercase letters and numbers but not negative or floating point numbers两种方法都将匹配大小写字母和数字,但不匹配负数或浮点数

Modify the Regular expression from [a-zA-Z0-9] to ^[a-zA-Z0-9]+$将正则表达式从[a-zA-Z0-9]^[a-zA-Z0-9]+$

String text="abcABC983";
System.out.println(text.matches("^[a-zA-Z0-9]+$"));

Current output: true当前输出: true

The regular expression character class \\p{Alnum} can be used in conjunction with String#matches .正则表达式字符类\\p{Alnum}可以与String#matches结合使用。 It is equivalent to [\\p{Alpha}\\p{Digit}] or [a-zA-Z0-9] .它相当于[\\p{Alpha}\\p{Digit}][a-zA-Z0-9]

boolean allLettersAndNumbers = str.matches("\\p{Alnum}*");
// Change * to + to not accept empty String

See the Pattern documentation .请参阅Pattern文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM