STRING SEARCH USING REGEX METHOD IN C#

Today in Engineer's World, we are discussing a very important topic of C# -String in very easy way. Posted By- +Manish Kumar Gautam +LIVE VIAR +ASP.NET SOLUTIONS

Click imaginationhunt.blogspot to see latest Blogs
 

REGEX SEARCH IN STRING

REGEX class is used to represent a Regular Expression. REGEX Searching in the string means an act to search a specified string object within the string. 

There are numerous ways of doing this: 
1) IsMatch()
2) Match()

IsMatch() Method

IsMatch() is used to tell whether the specified regular expression finds a match in the given string. It contains various matching options. It returns a boolean value, i.e. "true" if string object is found within string otherwise return "false".

We are explaining you the most used overload of IsMatch() method.

It contain 3 parameters(P):-
(P1) input: The string to search for a match.
(P2) pattern: The regular expression pattern to match.
(P3) options:
Enumeration values that provide options for matching. 

Match() Method

Match() is used to tell whether the first occurrence of the specified regular expression finds a match in the given string. It contains various matching options. It returns an object that contains information about the match.

We are explaining you the most used overload of Match() method. 


It contain 3 parameters(P):-
(P1) input: The string to search for a match.
(P2) pattern: The regular expression pattern to match.
(P3) options:
Enumeration values that provide options for matching.


Let's see all these method quickly by an example.

Example- C# program that uses all the above method.

Practical Implementation

using System;

namespace AspnetSolutions

{
    class SearchUsingRegex
    {
        public static void
Main() 
        {
            string strURL = "Url is imaginationhunt.blogspot which is run by Engineer's.";
          
            //Matching words start with 'i' and ends with 't':
            string pattern = @"\bi\S*t\b*"; // word is
imaginationhunt.blogspot 
            Console.WriteLine("Using IsMatch() Method");
            if (Regex.IsMatch(strURL, pattern, RegexOptions.IgnoreCase))
            {
                Console.WriteLine("Match found");
            }
            else
            {
                Console.WriteLine("Match not found");
            }
            Console.WriteLine();
            Console.WriteLine("----------------");


            Console.WriteLine("Using Match() Method");

            Match match = Regex.Match(strURL, pattern, RegexOptions.IgnoreCase);
            Console.WriteLine("Captured string in object match is ={0}",match.Value);
            if (match.Success)
            {
                Console.WriteLine("Match found");
            }
            else
            {
                Console.WriteLine("Match not found");
            }

        }
    }
}


Output


The expression matches the word "imaginationhunt.blogspot" and giving success message as "Match found" for both the cases.
[Note]: Captured string in object "match" is same as pattern(i.e. 'imaginationhunt.blogspot') string.

Let's interpret the pattern:

Click imaginationhunt.blogspot to see latest Blogs

Pattern: @"\bi\S*t\b*"

Pattern      Description
@            is the verbatim literal
\bi           Matches a word boundary(Ex- word start with char 'i')
\S           Matches any non-white space character
\tb           Matches a word boundary(Ex- word end with char 't')

Read more about Regular expression:
MSDN Regular Expression Language - Quick Reference
MSDN Regular Expression Syntax 

Applications

Regular expressions are the best way to search without writing any comparison code. Yes, it is not an easy task for developers to make a pattern. But, if made then any string identification, searching and validation become so easy, then doing by various lines of code and methods.


Various application with Regular expression to search strings are:1) Email validation
2) Search Email by pattern
3) URL search
4) Address Path
5) Date Validation
and many more...

To read IS STRING MUTABLE OR IMMUTABLE IN .NET? - Click here.


Related Questions:

#newtoprgm try first program

Q-1 How to validate an Email by Regular Expression?
Ans- User Input Code for validating an Email Address.

Practical Implementation

using System;

namespace AspnetSolutions

{
    class SearchUsingRegex
    {
        public static void
Main() 
        {
            //Email Validating

            Console.WriteLine("Enter your Email");
            string Email = Console.ReadLine();
            string EmailPattern = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";

            if (Regex.IsMatch(Email, EmailPattern, RegexOptions.IgnoreCase))
            {
                Console.WriteLine("Email: {0} is valid.", Email);
            }
            else
            {
                Console.WriteLine("Email: {0} is not valid.", Email);
            }
 
        }
    }
}


Output



Q-2 Which pattern is used to match white space character?
A) \s
B) \w
C) \d
D) \s\S


Ans- Option(A).
Explanation- 
\w is used to match any word character.(ex- "E"),
\s\S is to match non-white space character.(ex-"_", "img_1"),
\d is used to match any decimal charcter.(ex- "9")


Click imaginationhunt.blogspot to see latest Blogs

Keep learning and sharing...

Comments

Popular posts from this blog

SSC CGL 2016 Tier-1 Marks / Result

DATA TYPES IN C#

Pattern printing program

IS STRING MUTABLE OR IMMUTABLE IN .NET?

Top Mutual Funds

SSC CGL 2017 TIER 2 RESULT OUT

JUST IN TIME (JIT)

Can we have multiple Main methods in one class

TOP 15 VISUAL STUDIO SHORTCUT KEYS

Top 10 Interview Tips and Questions