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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33467536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 14:42:18  来源:igfitidea点击:

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

java

提问by unclesam

Let's say a user inputs text. How does one check that the corresponding Stringis 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)

回答by Manos Nikolaidis

  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 (char c : name.toCharArray()) {
        if (!Character.isLetterOrDigit(c)) {
            // found invalid char
            break;
        }
    }
    
  1. 使用正则表达式:

    Pattern pattern = Pattern.compile("\p{Alnum}+");
    Matcher matcher = pattern.matcher(name);
    if (!matcher.matches()) {
        // found invalid char
    }
    
  2. 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

两种方法都将匹配大小写字母和数字,但不匹配负数或浮点数

回答by Harsh Poddar

You can call matchesfunction on the string object. Something like

您可以matches在字符串对象上调用函数。就像是

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

回答by Prashant Pimpale

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