Regex Tutorial - How to write Regular Expressions?
Last Updated :
12 Apr, 2024
A regular expression (regex) is a sequence of characters that define a search pattern. Here's how to write regular expressions:
- Start by understanding the special characters used in regex, such as ".", "*", "+", "?", and more.
- Choose a programming language or tool that supports regex, such as Python, Perl, or grep.
- Write your pattern using the special characters and literal characters.
- Use the appropriate function or method to search for the pattern in a string.
Examples:
- To match a sequence of literal characters, simply write those characters in the pattern.
- To match a single character from a set of possibilities, use square brackets, e.g. [0123456789] matches any digit.
- To match zero or more occurrences of the preceding expression, use the star (*) symbol.
- To match one or more occurrences of the preceding expression, use the plus (+) symbol.
- 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
Getting started with Regular Expressions | Natural Language Processing
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem