| Dua Ali
A regular expression in C# makes it easier to accomplish the task of matching pattern of a string C#. Regex also known as C# regular expression is a sequence of characters that defines a pattern. A pattern can be containing literals, numbers, characters, operators. The pattern is used to search strings or files to see if matches are found. Regular expressions are often used in input validations, parsing, and finding strings. For example, checking for a valid date of birth, social security number, full name with a comma between the first and last names, identifying the number of occurrences of a substring, replacing substrings, date formats, valid email formats, currency formats, and so on.
Regex Class in C#
The regular expression engine is represented by the C# Regex class. It can parse vast volumes of text quickly to discover specific character patterns, extract, edit, replace, or delete text substrings, and add extracted strings to a collection to make a report.
In .NET Regex class is defined in the System.Text.RegularExpressions namespace. Remember to add this namespace before starting.
The following code creates a regex pattern. Here pattern is to match a country name starting with char ‘A’.
- A variable is initialized with pattern of words starting with [A].
- A regex is created for that pattern.
- We have a pattern of different countries in a string variable to which the regex would be matched.
- Here the matching between the string of country name and regular expression is done and stored in a Matched Collection.
- A loop is used to iterate the whole matched collection and print the result on console.
To ignore case, we can do it like that,
Taking another example, we can see that how regex can be used to split a string.
- Here we have a string that contains numbers also.
- Here an array is defined which takes up the split text (numbers) after being compared with the regex.
- A loop is defined to print the array of numbers.
As a result, we have got all the numbers which were present in the original string.
The same can be done with special characters. We can remove or add anything in place of a special character present in a string. This can be done as
- A string is defined in which a phone number is stored in its original format.
- Using regex.Replace, all the special characters are replaced with an empty string “”
- The result is printed on console.
As result, it is visible that all the special characters are removed from the string and we have got the resulted string.
Join us next time, as we continue our journey of learning canvas apps.Click here to learn more about Imperium's Power Apps Services. We hope this information was useful, and we look forward to sharing more insights into the Power Platform world.