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 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.

How to snooze an email in Gmail

How to snooze an email in Gmail With the popularity of Gmail, today every deal is likely to be discussed in emails. And with so many things rushing in the Inbox,...

3 minutes read.

How to clean a Computer Screen?

How to clean a computer screen Professionalism is a trait to possess attitude, neatness, and maintenance in every trail of business. Imagine, if you are designated as Marketing Manager, and you...

5 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 add contacts to Gmail?

How to add contacts to Gmail? Managing your inbox is a tiresome task, but one way to make it effortless and easier is to gain an add on the benefit of...

5 minutes read.

How to change Gmail Password?

How to change Gmail Password? Today Gmail account is linked to all your application and software unlike, Instagram, Facebook, and Skype, etc. You can log in to different platforms directly using...

6 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 take a screenshot on windows

How to take a screenshot on windows A screenshot is a picture taken on your computer. In this section, we will learn how to take screenshot on windows operating system. We can take screenshot...

5 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 a page in Microsoft Word?

What is Microsoft Word? Microsoft word is a word processing program, which is developed by Microsoft. It was initially launched on 25 October 1983 and has since been modified many times. Generally, Microsoft Word...

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 write a cover letter

How to write a cover letter The letter that you include with your job application is known as a cover letter. One is suggested to always include a cover letter with your job application...

5 minutes read.

How to address a letter (formal and in-formal)

How to address a letter In the generation of (SMS) and emails, it is still necessary to know how to address a letter for the one. Throughout the modern world, formal letters are...

7 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 take a Screenshot on computer?

How to take a Screenshot on computer The ScreenShot feature is widely used to procure the content of the screen as an image. This feature was introduced in the late ’90s,...

8 minutes read.

How to find archived emails in Gmail

How to find archived emails in Gmail Similar/Related Questions Where do Gmail archived emails go? How can Gmail users access archived emails? How to get to archived Gmail? In which folder does the archived Gmail...

4 minutes read.

How To Connect Air pods To Computer?

How To Connect Air pods To Computer Apple has put light on a statement and said that it believes the future is wireless. This technology is pacing up with the time,...

5 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 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.

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.