Regex or Regular Expressions are an important part of Perl Programming. It is used for searching the specified text pattern. In this, set of characters together form the search pattern. It is also known as regexp. Working with regex might become complex with more and more addition in functionalities. To reduce the complexity, Perl provides us with more operations such as Alternation and Grouping.
The name itself suggests the mechanism it does, first and foremost its like a (&&) operator which appears in ‘C’ programming language. The ‘&&’ operator in C works as until it finds that all the conditional statements are true it won’t return 1 and returns 0 as soon as it finds a false statement. The alternation in Perl works in both ways simultaneously. Alternation can be done using either the metacharacters ‘|’ or ‘’. Following examples will make things clear:
1 I found geek.
So, in the above example, it first checks for ‘geek’ and finds a match in the first alternate pattern returns 1 as soon as it finds a match. But it also checks for ‘for’ too and if it is not present in the string it won’t be bothered as it already returned the match status. If ‘for’ is a match, it checks whether ‘for’ is appearing in the least position of the string as ‘g’ in ‘geeks’ appears at position 0 and ‘f’ in ‘for’ appears at position 5, ‘geek’ gets stored in the last match pattern. Check out the following example:
$& - Contains the string matched by the last pattern match.
1 I found ge. g
Grouping is used to search for a pattern bounded with similar words or patterns, in the beginning, end or in the middle and it also returns the least positioned pattern. Grouping is done using metacharacter ‘()’. Following is an example which will make things clear:
I found Blackbackground.
For better understanding check out the following example:
Valid : Abemail@example.com Valid : firstname.lastname@example.org Valid : email@example.com
- Perl | 'ee' Modifier in Regex
- Perl | Assertions in Regex
- Perl | Anchors in Regex
- Perl | Regex Character Classes
- Perl | Searching in a File using regex
- Perl | Regex Cheat Sheet
- Perl | Extract IP Address from a String using Regex
- Perl | Basic Syntax of a Perl Program
- Perl Tutorial - Learn Perl With Examples
- Kotlin Grouping
- Grouping Rows in pandas
- ES6 | RegEx
- What is Regex in Golang?
- How to get YouTube video ID with PHP Regex ?
- Function to escape regex patterns before applied in PHP
- Split a String into columns using regex in pandas DataFrame
- Perl vs C/C++
- Perl | Variables
- Perl | GET vs POST in CGI
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.