Open In App

How to check string is alphanumeric or not using Regular Expression

Last Updated : 03 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given string str, the task is to check whether the string is alphanumeric or not by using Regular Expression

An alphanumeric string is a string that contains only alphabets from a-z, A-Z and some numbers from 0-9.

Examples: 

Input: str = “GeeksforGeeks123” 
Output: true 
Explanation: 
This string contains all the alphabets from a-z, A-Z, and the number from 0-9. Therefore, it is an alphanumeric string.
Input: str = “GeeksforGeeks” 
Output: false 
Explanation: 
This string contains all the alphabets from a-z, A-Z, but doesn’t contain any number from 0-9. Therefore, it is not an alphanumeric string.
Input: str = “GeeksforGeeks123@#” 
Output: false 
Explanation: 
This string contains all the alphabets from a-z, A-Z, and the number from 0-9 along with some special symbols. Therefore, it is not an alphanumeric string. 
 

Approach: This problem can be solved by using Regular Expression. 

  • Get the string.
  • Create a regular expression to check string is alphanumeric or not as mentioned below: 
regex = "^(?=.*[a-zA-Z])(?=.*[0-9])[A-Za-z0-9]+$";
  • Where: 
    • ^ represents the starting of the string
    • (?=.*[a-zA-Z]) represents the alphabets from a-z, A-Z
    • (?=.*[0-9]) represents any number from 0-9
    • [A-Za-z0-9] represents whether everything is either alphabetical or digit
    • + represents one or more times
    • $ represents the ending of the string
  • Match the given string with the regex, in Java, this can be done by using Pattern.matcher()
  • Return true if the string matches with the given regex, else return false

Below is the implementation of the above approach.
 

C++




// C++ program to check
 
// String is alphanumeric or not using Regular Expression
#include <iostream>
#include <regex>
 
using namespace std;
 
// Function to validate the // String is alphanumeric or not using Regular Expression
bool isAlphaNumeric(string str) {
 
// Regex to check valid  alphanumeric String.
  const regex pattern("^(?=.*[a-zA-Z])(?=.*[0-9])[A-Za-z0-9]+$");
 
// If the string
 
// is empty return false
  if (str.empty())
  {
    return false;
  }
 
 
// Return true if the String
 
// matched the ReGex
 
if (regex_match(str, pattern))
{
return true;;
}
else
{
  return false;
}
}
 
// Driver Code
 
int main()
 
{
  // Test Case 1:
string str1= "GeeksforGeeks123";
cout <<isAlphaNumeric(str1) << endl;
 
// Test Case 2:
 
string str2= "GeeksforGeeks";
 cout << isAlphaNumeric(str2) << endl;
 
// Test Case 3:
 
string str3= "GeeksforGeeks123@#";
cout << isAlphaNumeric(str3) << endl;
 
// Test Case 4:
 
string str4= "123";
cout << isAlphaNumeric(str4) << endl;
//Test Case 5:
 
string str5="@#";
cout << isAlphaNumeric(str5) << endl;
 
return 0;
}
 
//This Code is contributed by Rahul Chauhan


Java




// Java program to check string is
// alphanumeric or not using Regular Expression.
 
import java.util.regex.*;
 
class GFG {
 
    // Function to check string is alphanumeric or not
    public static boolean isAlphaNumeric(String str)
    {
        // Regex to check string is alphanumeric or not.
        String regex = "^(?=.*[a-zA-Z])(?=.*[0-9])[A-Za-z0-9]+$";
 
        // Compile the ReGex
        Pattern p = Pattern.compile(regex);
 
        // If the string is empty
        // return false
        if (str == null) {
            return false;
        }
 
        // Pattern class contains matcher() method
        // to find matching between given string
        // and regular expression.
        Matcher m = p.matcher(str);
 
        // Return if the string
        // matched the ReGex
        return m.matches();
    }
 
    // Driver Code.
    public static void main(String args[])
    {
 
        // Test Case 1:
        String str1 = "GeeksforGeeks123";
        System.out.println(
            str1 + ": "
            + isAlphaNumeric(str1));
 
        // Test Case 2:
        String str2 = "GeeksforGeeks";
        System.out.println(
            str2 + ": "
            + isAlphaNumeric(str2));
 
        // Test Case 3:
        String str3 = "GeeksforGeeks123@#";
        System.out.println(
            str3 + ": "
            + isAlphaNumeric(str3));
 
        // Test Case 4:
        String str4 = "123";
        System.out.println(
            str4 + ": "
            + isAlphaNumeric(str4));
 
        // Test Case 5:
        String str5 = "@#";
        System.out.println(
            str5 + ": "
            + isAlphaNumeric(str5));
    }
}


Python3




# Python3 program to check
# string is alphanumeric or
# not using Regular Expression.
import re
 
# Function to check string
# is alphanumeric or not
def isAlphaNumeric(str):
 
    # Regex to check string is
    # alphanumeric or not.
    regex = "^(?=.*[a-zA-Z])(?=.*[0-9])[A-Za-z0-9]+$"
 
    # Compile the ReGex
    p = re.compile(regex)
 
    # If the string is empty
    # return false
    if(str == None):
        return False
 
    # Return if the string
    # matched the ReGex
    if(re.search(p, str)):
        return True
    else:
        return False
 
# Driver Code
 
# Test Case 1:
str1 = "GeeksforGeeks123"
print(str1, ":",
      isAlphaNumeric(str1))
 
# Test Case 2:
str2 = "GeeksforGeeks"
print(str2, ":",
      isAlphaNumeric(str2))
 
# Test Case 3:
str3 = "GeeksforGeeks123@#"
print(str3, ":",
      isAlphaNumeric(str3))
 
# Test Case 4:
str4 = "123"
print(str4, ":",
      isAlphaNumeric(str4))
 
# Test Case 5:
str5 = "@#"
print(str5, ":",
      isAlphaNumeric(str5))
 
# This code is contributed by avanitrachhadiya2155


C#




// C# program to check
// String is alphanumeric or not using Regular Expression
using System;
using System.Text.RegularExpressions;
class GFG
{
 
  // Main Method
  static void Main(string[] args)
  {
 
    // Input strings to Match
    // String is alphanumeric or not
    string[] str={"GeeksforGeeks123","GeeksforGeeks" ,
                  "GeeksforGeeks123@#","123",
                  "@#"};
    foreach(string s in str) {
      Console.WriteLine( isAlphaNumeric(s) ? "true" : "false");
    }
    Console.ReadKey(); }
 
  // method containing the regex
  public static bool isAlphaNumeric(string str)
  {
    string strRegex = @"^(?=.*[a-zA-Z])(?=.*[0-9])[A-Za-z0-9]+$";
    Regex re = new Regex(strRegex);
    if (re.IsMatch(str))
      return (true);
    else
      return (false);
  }
}
 
// This code is contributed by Rahul Chauhan


Javascript




// Javascript program to check
// String is alphanumeric or not using Regular Expression
 
// Function to validate the
// string
function isAlphaNumeric(str) {
    // Regex to check valid
    // alphanumeric string 
    let regex = new RegExp(/^(?=.*[a-zA-Z])(?=.*[0-9])[A-Za-z0-9]+$/);
 
    // if str
    // is empty return false
    if (str == null) {
        return "false";
    }
 
    // Return true if the str
    // matched the ReGex
    if (regex.test(str) == true) {
        return "true";
    }
    else {
        return "false";
    }
}
 
// Driver Code
// Test Case 1:
let str1 = "GeeksforGeeks123";
console.log(isAlphaNumeric(str1));
 
// Test Case 2:
let str2 = "GeeksforGeeks";
console.log(isAlphaNumeric(str2));
 
// Test Case 3:
let str3 = "GeeksforGeeks123@#";
console.log(isAlphaNumeric(str3));
 
// Test Case 4:
let str4 = "#123";
console.log(isAlphaNumeric(str4));
 
// Test Case 5:
let str5 = "#@#";
console.log(isAlphaNumeric(str5));
 
// This code is contributed by Rahul Chauhan


Output: 

GeeksforGeeks123: true
GeeksforGeeks: false
GeeksforGeeks123@#: false
123: false
@#: false

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads