Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

Let's say a user inputs text. How does one check that the corresponding String is made up of only letters and numbers?

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)
like image 758
unclesam Avatar asked Nov 01 '15 21:11

unclesam


People also ask

How do you check if the string contains only letters or digits?

To check whether a String contains only unicode letters or digits in Java, we use the isLetterOrDigit() method and charAt() method with decision-making statements. The isLetterOrDigit(char ch) method determines whether the specific character (Unicode ch) is either a letter or a digit.

How do you check if a string contains only alphabets and numbers in C?

In C programming, isalpha() function checks whether a character is an alphabet (a to z and A-Z) or not. If a character passed to isalpha() is an alphabet, it returns a non-zero integer, if not it returns 0. The isalpha() function is defined in <ctype. h> header file.


2 Answers

You can call matches function on the string object. Something like

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

This method will return true if the string only contains letters or numbers.

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

Regex tester and explanation: https://regex101.com/r/kM7sB7/1

like image 123
Harsh Poddar Avatar answered Sep 24 '22 17:09

Harsh Poddar


  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;
        }
    }
    

Both methods will match upper and lowercase letters and numbers but not negative or floating point numbers

like image 42
Manos Nikolaidis Avatar answered Sep 25 '22 17:09

Manos Nikolaidis