How to Check String is Alphanumeric or Not Using Regular Expression

If we have a string and want to know whether it is either alphanumeric or not, we can do it using Regular Expression(regex).

What is Regular Expression?

A Regular Expressionor regexis a series of characters and symbols representing a pattern or string to be explored in a lengthy text.

History of Regular Expression

The word “Regular Expression” came into existence in 1951, when regular languages were described by mathematician Stephen Cole Kleene using his mathematical script called regular events.

Use of Regular Expressions

These expressions became popular in 1968, especially for lexical analysis in a compiler and pattern matching in a text editor.

Regular Expressions are widely used in text fining tasks, and generally in the processing of strings, where data present may or may not be textual. Some of its common applications are Data Collection, Simple Parsing, etc.

Advantages of Regular Expressions

  • It can be used widely. For example, we can create one regular expression according to our need.
  • Almost every programming language supports these expressions, only a few of them does not understand regular expressions.
  • Greater number of tasks can be performed using them.
  • Code is more optimized and looks cleaner.
  • Faster authentication. For example, instead of using multiple If and Else conditions, we can authenticate in one go using them.

Note: The string containing both alphabets (from a-z, A-Z) and numbers (from 0-9) only is called an alphanumeric string. A string containing any other characters is not considered alphanumeric.)

Examples:

Input: st = “GoodMorning123” 
Output: True 

Description:

Since string ‘st’ contains alphabets (a-z, A-Z) and numbers (0-9) only, therefore it’s an alphanumeric string.

Input: st = “GoodMorning” 
Output: False 

Description:

Since string ‘st’ contains alphabets (a-z, A-Z) but does not contain numbers (0-9), therefore it is not an alphanumeric string.

Input: st = “Good_Morning!@#” 
Output: False 

Description:

Since string ‘st’ contains alphabets (a-z, A-Z) but it does not contain numbers (0-9) and in addition to that it also contains some special characters, therefore it is not an alphanumeric string.

Input: st = “GoodMorning123!@#”
Output: False

Description:

Since string ‘st’ contains alphabets (a-z, A-Z) and numbers (0-9) but in addition to that it also has some special characters, therefore it cannot be considered an alphanumeric string.

Now, what is the procedure to be followed to get the required work done?

Firstly, we will create a function to check whether the string is alphanumeric or not using Regular Expression as shown below:

regex = “^(?=.*[a-zA-Z])(?=.*[0-9])[A-Za-z0-9]+$”;

In the above expression:

  • ^is regarded as the beginning of the string.
  • “^(?=.*[a-zA-Z])shows the alphabets from ‘a to z’ in both uppercase and lowercase.
  • (?=.*[0-9]) shows any number from ‘0 to 9’.
  • [A-Za-z0-9] represents whether every character is either an alphabet or a digit.
  • + represents a number of repetitions.
  • $ is regarded as the end of the string.

Then we will use the given string with regex and if the given string matches with the regex, we will return True as output or else return False as output.

Example:

// A program in java to check whether the given string
// is alphanumeric or not using regex
 
importjava.util.regex.*;
 
classGFG {
 
    //User-defined function to check the given string
    publicstaticbooleanisAN(String st)
    {
        // initialization of regex
        String regex = “^(?=.*[a-zA-Z])(?=.*[0-9])[A-Za-z0-9]+$”;
 
        // Compiling regex
        Pattern x = Pattern.compile(regex);
 
        //return false if there is no content in the string
        if(st == null) {
            returnfalse;
        }
 
        // matcher() is the pre-defined used to compare
        // given string and regular function
        Matcher y = x.matcher(str);
 
        // Give back if the given string
        // matcheswithregex
        returny.matches();
    }
 
    // main code
    publicstaticvoidmain(String args[])
    {
 
        // case-I:
        String st1 = “GoodMorning1234”;
        System.out.println(
            St1 + “: “
            + isAN(st1));
 
        // case-II:
        String st2 = “GoodMorning”;
        System.out.println(
            st2 + “: “
            + isAN(st2));
 
        // case-III:
        String st3 = “Good_Morning123!@#”;
        System.out.println(
            st3 + “: “
            + isAN(st3));
 
        // case-IV:
        String st4 = “12345”;
        System.out.println(
            st4 + “: “
            + isAN(st4));
 
        // case- V:
        String st5 = “!@#$”;
        System.out.println(
            st5 + “: “
            + isAN(st5));
    }
}

Output:

GoodMorning1234: True
GoodMorning: False
Good_Morning123!@#: False
12345: False
!@#$: False

Related Topics

How to backup iPhone to Computer?

How to backup iPhone to computer iPhone or iPad is an electronic gadget useful to store all preferences, memories, personal or official data, unlike essential documents, emails, messages, photos, running apps,...

6 minutes read.

How to select all in Gmail

How to select all in Gmail Undoubtedly Gmail is one of the leading email service providers across the world. Teenagers, adults, old ages all rely upon Gmail because of its free...

3 minutes read.

How to Create a Group Email in Gmail

How to Create a Group Email in Gmail Every now and then, one needs to pass on or share a message to several people at the same time. To make this...

6 minutes read.

How to Check String is Alphanumeric or Not Using Regular Expression

If we have a string and want to know whether it is either alphanumeric or not, we can do it using Regular Expression(regex). What is Regular Expression? A Regular Expressionor regexis a...

3 minutes read.

How to delete Snapchat Account?

What is Snapchat? Snapchat is a social networking app, which is developed by Snap Inc. It is created by Even Spiegel, Bobby Murphy, and Reggie Brown. Snapchat was launched in September 2011. It is...

3 minutes read.

How to Make Money Online?

How to make money online? Earning money from the traditional way of working is a way harder and requires a lot of manpower and capital. With the increase in the use of the Internet...

9 minutes read.

How to Find Element in Rotated Sorted Array?

In this article, we are going to find the element in a rotated sorted array using the programs in different computer languages like Java and C++. We are going to...

3 minutes read.

How to Multiply Fractions?

What is a Fraction? A fraction is a number that divides a whole number into equal parts. A fraction tells us how many parts we have from the whole part. We...

2 minutes read.

How to find your Computer’s specs?

How to find your computer’s specs The computer specs include the details for every single component in your computer, including your CPU, hard drive space, and even the little things like...

7 minutes read.

How to accelerate the speed of loading images on any website?

No website can be successful without attractive and relevant images or pictures. In the current time, the users want speedy information about their searches on the internet browser. The image...

3 minutes read.

How to flip your Computer Screen

How to flip your computer screen The word flip refers to turn over or rotate something quickly. Computers provide the flip functionality, which facilitates the providers to rotate the screen in...

5 minutes read.

How to change Computer Name?

How to change computer name Today computers are all around us and have become an indispensable part of our lives. Every computer generally has a name attached to it. There might...

6 minutes read.

How to schedule an email in Gmail?

How to schedule an email in Gmail Imagine scenarios where you send an important message to one of your international clients, and you know the time difference is significant. Earlier, you...

7 minutes read.

How to Find Divisors of a Number?

A number that equally divides a larger integer is referred to as a divisor or factor. By simply listing all the possible methods to multiply two numbers together to obtain...

3 minutes read.

Does my computer have Bluetooth?

Does my computer have Bluetooth? With the advancement of IOT (Internet of things) and high-tech electronic gadgets, Bluetooth has become perennial in our digital lives. Most of us are already familiar...

6 minutes read.

How to write a cheque?

How to write a cheque? In today's time, digital payments are consistently gaining more market share, but it's also important to know how to write a cheque. Many companies, employers, workers, and landlords still...

2 minutes read.

How to Delete Facebook Account?

How to Delete Facebook Account Facebook is a social networking platform that helps you to quickly communicate and share online with your family and friends. Initially developed for college students, Mark Zuckerberg founded Facebook...

3 minutes read.

How to delete Gmail Account?

What is Gmail? Gmail is a free mobile and web-based email service introduced by Google on April 1, 2004. Gmail is used for personal to business purposes. It allows users to...

2 minutes read.

How to compress jpeg file to 100kb?

Nowadays, everyone loves to share cool snapshots on social media handles. Before putting the images on any site, editing is an integral part. File compression is one of method by...

3 minutes read.

What does RAM do on a computer?

What does RAM do on a computer? Many of us might have heard the word RAM in our daily life but do not know what it does except the fact that...

10 minutes read.