(Translated by https://www.hiragana.jp/)
Regex Tutorial - How to write Regular Expressions? - GeeksforGeeks
Open In App

Regex Tutorial – How to write Regular Expressions?

Last Updated : 12 Apr, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Basic
71.6%
9.6K

A regular expression (regex) is a sequence of characters that define a search pattern. Here’s how to write regular expressions:

  1. Start by understanding the special characters used in regex, such as “.”, “*”, “+”, “?”, and more.
  2. Choose a programming language or tool that supports regex, such as Python, Perl, or grep.
  3. Write your pattern using the special characters and literal characters.
  4. Use the appropriate function or method to search for the pattern in a string.

Examples:

  1. To match a sequence of literal characters, simply write those characters in the pattern.
  2. To match a single character from a set of possibilities, use square brackets, e.g. [0123456789] matches any digit.
  3. To match zero or more occurrences of the preceding expression, use the star (*) symbol.
  4. To match one or more occurrences of the preceding expression, use the plus (+) symbol.
  5. It is important to note that regex can be complex and difficult to read, so it is recommended to use tools like regex testers to debug and optimize your patterns.

A regular expression (sometimes called a rational expression) is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings, or string matching, i.e. “find and replace” like operations. Regular expressions are a generalized way to match patterns with sequences of characters. It is used in every programming language like C++, Java and Python. 

What is a regular expression and what makes it so important? 

Regex is used in Google Analytics in URL matching in supporting search and replaces in most popular editors like Sublime, Notepad++, Brackets, Google Docs, and Microsoft Word.

Example :  Regular expression for an email address :
^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$

The above regular expression can be used for checking if a given set of characters is an email address or not. 

How to write regular expressions?

There are certain elements  used to write regular expressions as mentioned below:

1. Repeaters (  *, +, and { } )  

These symbols act as repeaters and tell the computer that the preceding character is to be used for more than just one time.

2. The asterisk symbol ( * )

It tells the computer to match the preceding character (or set of characters) for 0 or more times (upto infinite).

Example : The regular expression ab*c will give ac, abc, abbc, abbbc….and so on 

3. The Plus symbol ( + ) 

It tells the computer to repeat the preceding character (or set of characters) at atleast one or more times(up to infinite).

Example : The regular expression ab+c will give abc, abbc,
abbbc, … and so on.

4. The curly braces { … } 

It tells the computer to repeat the preceding character (or set of characters) for as many times as the value inside this bracket.

Example : {2} means that the preceding character is to be repeated 2 
times, {min,} means the preceding character is matches min or more
times. {min,max} means that the preceding character is repeated at
least min & at most max times.

5. Wildcard ( . ) 

The dot symbol can take the place of any other symbol, that is why it is called the wildcard character.

Example : 
The Regular expression .* will tell the computer that any character
can be used any number of times.

6. Optional character ( ? ) 

This symbol tells the computer that the preceding character may or may not be present in the string to be matched.

Example : 
We may write the format for document file as – “docx?”
The ‘?’ tells the computer that x may or may not be
present in the name of file format.

7. The caret ( ^ ) symbol ( Setting position for the match )

The caret symbol tells the computer that the match must start at the beginning of the string or line.

Example : ^\d{3} will match with patterns like "901" in "901-333-".

8.  The dollar ( $ ) symbol 

It tells the computer that the match must occur at the end of the string or before \n at the end of the line or string.

Example : -\d{3}$  will match with patterns like "-333" in "-901-333".

9. Character Classes 

A character class matches any one of a set of characters. It is used to match the most basic element of a language like a letter, a digit, a space, a symbol, etc. 

\s: matches any whitespace characters such as space and tab.
\S: matches any non-whitespace characters.
\d: matches any digit character.
\D: matches any non-digit characters.
\w : matches any word character (basically alpha-numeric)
\W: matches any non-word character.
\b: matches any word boundary (this would include spaces, dashes, commas, semi-colons, etc.
[set_of_characters]: Matches any single character in set_of_characters. By default, the match is case-sensitive.

Example : [abc] will match characters a,b and c in any string.

10. [^set_of_characters] Negation: 

Matches any single character that is not in set_of_characters. By default, the match is case-sensitive.

Example : [^abc] will match any character except a,b,c .

11. [first-last] Character range: 

Matches any single character in the range from first to last.

Example : [a-zA-z] will match any character from a to z or A to Z.

12. The Escape Symbol (  \  ) 

If you want to match for the actual ‘+’, ‘.’ etc characters, add a backslash( \ ) before that character. This will tell the computer to treat the following character as a search character and consider it for a matching pattern.

Example : \d+[\+-x\*]\d+ will match patterns like "2+2"
and "3*9" in "(2+2) * 3*9".

13. Grouping Characters ( ) 

A set of different symbols of a regular expression can be grouped together to act as a single unit and behave as a block, for this, you need to wrap the regular expression in the parenthesis( ).

Example : ([A-Z]\w+) contains two different elements of the regular 
expression combined together. This expression will match any pattern
containing uppercase letter followed by any character.

14. Vertical Bar (  |  ) 

Matches any one element separated by the vertical bar (|) character.

Example :  th(e|is|at) will match words - the, this and that.

15. \number 

Backreference: allows a previously matched sub-expression(expression captured or enclosed within circular brackets ) to be identified subsequently in the same regular expression. \n means that group enclosed within the n-th bracket will be repeated at current position.

Example : ([a-z])\1 will match “ee” in Geek because the character 
at second position is same as character at position 1 of the match.

16. Comment ( ?# comment ) 

Inline comment: The comment ends at the first closing parenthesis.

Example : \bA(?#This is an inline comment)\w+\b

17. # [to end of line] 

X-mode comment. The comment starts at an unescaped # and continues to the end of the line.

Example :  (?x)\bA\w+\b#Matches words starting with A


Previous Article
Next Article

Similar Reads

std::regex_match, std::regex_replace() | Regex (Regular Expression) In C++
Regex is the short form for “Regular expression”, which is often used in this way in programming languages and many different libraries. It is supported in C++11 onward compilers.Function Templates used in regex regex_match() -This function return true if the regular expression is a match against the given string otherwise it returns false. C/C++ C
3 min read
Extracting email addresses using regular expressions in Python
Let suppose a situation in which you have to read some specific data like phone numbers, email addresses, dates, a collection of words etc. How can you do this in a very efficient manner?The Best way to do this by Regular Expression. Let take an example in which we have to find out only email from the given input by Regular Expression. Examples: In
3 min read
Regular Expressions to Validate Google Analytics Tracking Id
Given some Google Analytics Tracking IDs, the task is to check if they are valid or not using regular expressions. Rules for the valid Tracking Id are: It is an alphanumeric string i.e., containing digits (0-9), alphabets (A-Z), and a Special character hyphen(-).The hyphen will come in between the given Google Analytics Tracking Id.Google Analytics
5 min read
How to validate a Username using Regular Expressions in Java
Given a string str which represents a username, the task is to validate this username with the help of Regular Expressions. A username is considered valid if all the following constraints are satisfied: The username consists of 6 to 30 characters inclusive. If the username consists of less than 6 or greater than 30 characters, then it is an invalid
3 min read
Regular Expressions to Validate Provident Fund(PF) Account Number
Given some PF(Provident Fund) Account Number, the task is to check if they are valid or not using regular expressions. Rules for the valid PF Account Number are : PF account number is alphanumeric String and forward slaces.First five characters are reserved for alphabet letters.Next 17 characters are reserved for digits(0-9).It allows only special
5 min read
Count occurrences of a word in string | Set 2 (Using Regular Expressions)
Given a string str and a word w, the task is to print the number of the occurrence of the given word in the string str using Regular Expression. Examples: Input: str = "peter parker picked a peck of pickled peppers”, w = "peck"Output: 1Explanation: There is only one occurrence of the word "peck" in the given string. Therefore, the output is 1. Inpu
4 min read
US currency validation using Regular Expressions
Given some US Currencies, the task is to check if they are valid or not using regular expressions. Rules for the valid Currency are: It should always start with "$".It can contain only digits (0 - 9) and at most one dot.It should not contain any whitespaces and alphabets.Comma Separator (', ') should be there after every three digits interval. Exam
5 min read
Extracting PAN Number from GST Number Using Regular Expressions
Given a string str in the form of a GST Number, the task is to extract the PAN Number from the given string. General Format of a GST Number: "22AAAAA0000A1Z5" 22: State CodeAAAAA0000A: Permanent Account Number (PAN)1: Entity Number of the same PANZ: Alphabet Z by default5: Checksum digit Examples: Input: str="23BOSPC9911R2Z5Output: BOSPC9911R Input
4 min read
How to validate ISIN using Regular Expressions
ISIN stands for International Securities Identification Number. Given string str, the task is to check whether the given string is a valid ISIN(International Securities Identification Number) or not by using Regular Expression. The valid ISIN(International Securities Identification Number) must satisfy the following conditions: It Should be the com
6 min read
Validating UPI IDs using Regular Expressions
Given some UPI IDs, the task is to check if they are valid or not using regular expressions. Rules for the valid UPI ID: UPI ID is an alphanumeric String i.e., formed using digits(0-9), alphabets (A-Z and a-z), and other special characters.It must contain '@'.It should not contain whitespace.It may or may not contain a dot (.) or hyphen (-). UPI st
6 min read
Validate Gender using Regular Expressions
Given some words of Gender, the task is to check if they are valid or not using regular expressions. The correct responses can be as given below: Male / male / MALE / M / mFemale / female / FEMALE / F / fNot prefer to say Example: Input: MOutput: True Input: SOutput: False Approach: The problem can be solved based on the following idea: Create a re
6 min read
Validating Programming File formats using Regular Expressions
Given some programming file names, the task is to check if they are valid or not using regular expressions. A valid programming file name follows the below conditions: It can contain alphabets (UpperCase or LowerCase), and digits and may contain a hyphen.It should contain one dot only that will be used as a suffix to save the file.Avoid special cha
6 min read
Regular Expressions to Validate ISBN Code
Given some ISBN Codes, the task is to check if they are valid or not using regular expressions. Rules for the valid codes are: It is a unique 10 or 13-digit.It may or may not contain a hyphen.It should not contain whitespaces and other special characters.It does not allow alphabet letters. Examples: Input: str = ”978-1-45678-123-4?Output: True Inpu
5 min read
Pension Scheme Tax Reference Number Validation using Regular Expressions
Given some Pension Scheme Tax Reference Numbers, the task is to check if they are valid or not using regular expressions. Rules for the valid Tax Reference Numbers are : It is an alphanumeric string ie., digits(0-9) and Uppercase Alphabet letters(A-Z).It does not contain whitespaces and other special characters.It starts with a digit and ends wends
6 min read
Extracting all present dates in any given String using Regular Expressions
Given a string Str, the task is to extract all the present dates from the string. Dates can be in the format i.e., mentioned below: DD-MM-YYYYYYYY-MM-DDDD Month YYYY Examples: Input: Str = "The First Version was released on 12-07-2008.The next Release will come on 12 July 2009. The due date for payment is 2023-09-1. India gained its freedom on 15 A
6 min read
Regular Expressions to validate Loan Account Number (LAN)
Given some Loan Account Number(LAN), the task is to check if they are valid or not using regular expressions. Rules for the valid Loan Account Number are: LAN is an alphanumeric string i.e., contains only digits (0-9) and uppercase alphabet characters.It does not allow whitespaces in it.It does not contain special characters.It starts with Uppercas
5 min read
Regular Expressions to Validate Account Office Reference Number
Given some Account Office Reference Number, the task is to check if they are valid or not using regular expressions. Rules for the valid Account Office Reference Number are: It is an alphanumeric string containing upper-case letters and digits.Accounts Office Reference Number is a unique, 13-character code.It starts with digits (0-9) and ends with
5 min read
Extracting all Email Ids in any given String using Regular Expressions
Given a string str, the task is to extract all the Email ID's from the given string. Example: Input: "Please send your resumes to Hr@Iwillgetbacktoyou@gmail.com for any business inquiry please mail us at business@enquiry@gmail.com"Output: Hr@Iwillgetbacktoyou@gmail.combusiness@enquiry@gmail.com Approach: The problem can be solved based on the follo
4 min read
Extracting Repository Name from a Given GIT URL using Regular Expressions
Given a string str, the task is to extract Repository Name from the given GIT URL. Examples: GIT URL can be any of the formats mentioned below: Input: str="git://github.com/book-Store/My-BookStore.git"Output: My-BookStoreExplanation: The Repo Name of the given URL is: My-BookStore Input: str="git@github.com:book-Store/My-BookStore.git"Output: My-Bo
4 min read
Extracting Port Number from a localhost API Request to a Server using Regular Expressions
Given a String test_str as localhost API Request Address, the task is to get the extract port number of the service. Examples: Input: test_str = ‘http://localhost:8109/users/addUsers’Output: 8109Explanation: Port Number, 8109 extracted. Input: test_str = ‘http://localhost:1337/api/products’Output: 1337Explanation: Port Number, 1337 extracted. Appro
5 min read
Match a pattern and String without using regular expressions
Given a string, find out if string follows a given pattern or not without using any regular expressions. Examples: Input: string - GraphTreesGraph pattern - aba Output: a->Graph b->Trees Input: string - GraphGraphGraph pattern - aaa Output: a->Graph Input: string - GeeksforGeeks pattern - GfG Output: G->Geeks f->for Input: string - G
11 min read
Validating Indian currency data using Regular expressions
Given some Indian Currency Data, the task is to check if they are valid or not using regular expressions. Rules for valid Indian Currency Data are: Indian Rupee format: The currency string starts with the Indian Rupee symbol ₹, followed by a comma-separated integer part that can have one to three digits, followed by a decimal point, followed by exa
5 min read
Regex in Python to put spaces between words starting with capital letters
Given an array of characters, which is basically a sentence. However, there is no space between different words and the first letter of every word is in uppercase. You need to print this sentence after the following amendments: Put a single space between these words. Convert the uppercase letters to lowercase Examples: Input : BruceWayneIsBatmanOut
2 min read
Python Regex to extract maximum numeric value from a string
Given an alphanumeric string, extract maximum numeric value from that string. Alphabets will only be in lower case. Examples: Input : 100klh564abc365bgOutput : 564Maximum numeric value among 100, 564 and 365 is 564.Input : abchsd0sdhsOutput : 0Python Regex to extract maximum numeric value from a stringThis problem has existing solution please refer
2 min read
Find all the patterns of “1(0+)1” in a given string using Python Regex
A string contains patterns of the form 1(0+)1 where (0+) represents any non-empty consecutive sequence of 0’s. Count all such patterns. The patterns are allowed to overlap. Note : It contains digits and lowercase characters only. The string is not necessarily a binary. 100201 is not a valid pattern. Examples: Input : 1101001 Output : 2 Input : 1000
2 min read
Program to check the validity of password without using regex.
Password checker program basically checks if a password is valid or not based on the password policies mention below: Password should not contain any space. Password should contain at least one digit(0-9). Password length should be between 8 to 15 characters. Password should contain at least one lowercase letter(a-z). Password should contain at lea
9 min read
How to validate an IP address using ReGex
Given an IP address, the task is to validate this IP address with the help of Regex (Regular Expression) in C++ as a valid IPv4 address or IPv6 address. If the IP address is not valid then print an invalid IP address. Examples: Input: str = "203.120.223.13" Output: Valid IPv4 Input: str = "000.12.234.23.23" Output: Invalid IP Input: str = "2F33:12a
5 min read
Get the first letter of each word in a string using regex in Java
Given a string, extract the first letter of each word in it. "Words" are defined as contiguous strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z. Examples: Input : Geeks for geeks Output :Gfg Input : United Kingdom Output : UK Below is the Regular expression to extract the first letter of each word. It uses '/b'(on
1 min read
Extract maximum numeric value from a given string | Set 2 (Regex approach)
Given an alphanumeric string, extract maximum numeric value from that string. Examples: Input : 100klh564abc365bg Output : 564 Maximum numeric value among 100, 564 and 365 is 564. Input : abchsd0365sdhs Output : 365Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. In Set 1, we have discussed general approach for ex
7 min read
Balanced expressions such that given positions have opening brackets | Set 2
Given an integer n and an array of positions ‘position[]’ (1 <= length(position[]) <= 2n), find the number of ways of proper bracket expressions that can be formed of length 2n such that given positions have the opening bracket. Note: position[] array is given in the form of (1-based indexing) [0, 1, 1, 0]. Here 1 denotes the positions at whi
15+ min read
Article Tags :
Practice Tags :