Regular Expressions, also known as Regex, in C# define patterns that are used to match, find, or replace text inside C# strings. A regex pattern is a special string that defines the criteria using which a string is searched, matched, or replaced.

In addition to Regex, the String and Array classes in C# language contain a variety of functions that provide string manipulation capabilities. For example, split(), indexOf(), find() etc.

Both Regex and String/Array functions offer string manipulation functionalities such as splitting strings and finding specific elements within a string etc.

In this article, you will see how to use Regex and String functions to split a string, to find an index of a string within another string, and to find different elements within a string, with the help examples. At the end of each section, a final verdict is given about whether to use Regex or String/Array functions in order to perform the corresponding tasks.
Table of Contents

  1. Regular Expression vs split()
  2. Regular Expressions vs IndexOf()
  3. Regular Expressions vs find()

Regular Expression vs split()

The split() functions from both the  String class and the Regex library returns a string split into tokens. In this section, you will see both ways of splitting strings in C#.

Regex.Split()

The Split() function from Regex can be used to split a string in C#. Furthermore, In C# String.split() function also splits a string.

Let’s see a simple example of how to split a string with the Regex.Split() function.

using System;
using System.Text.RegularExpressions;

namespace RegexCodes
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = "Hello*welcome to*C#";
            foreach (var tokens in Regex.Split(text, @"\*"))
                Console.WriteLine(tokens);
            
            Console.WriteLine("\nWith delimiters =========\n");

            string text2 = "Hello*welcome to* C#";
            foreach (var tokens in Regex.Split(text, @"(\*)"))
                Console.WriteLine(tokens);

        }
           
    }
}

In the script above, the Regex.Split() function splits the text “Hello*welcome to*C#” using the asterisk as a delimiter. The first parameter to the Regex.Split() function is the text string, while the second parameter is the Regex expression that is to be matched. The Regex expression used is @“\*”. This Regex expression splits a string at indexes where asterisk occurs. In the output, the asterisk itself is not included.

Next, in order to include delimiter asterisk in the out, the regex expression @”(\*)” splits the string. Notice round brackets in the regular expression, these round brackets tell the Split() function to include the delimiter in the split string.

Here is the output of the script:

Hello
welcome to
C#

With delimiters =========

Hello
*
welcome to
*
C#

The output clearly shows that the first script doesn’t include delimiters while the second script included delimiter while splitting a string.

String.Split()

Alternatively, you can use String.Split() function to split a string. With String.Split() function, you simply need to pass the delimiter that you want to use to split a string.

Here is an example:

using System;
using System.Text.RegularExpressions;

namespace RegexCodes
{
    class Program
    {
        static void Main(string[] args)
        {
      
            string text3 = "Hello * welcome to * C#";
            foreach (var tokens in text3.Split("*"))
                Console.WriteLine(tokens);

            Console.WriteLine("With delimiters =========");

            string text4 = "Hello * welcome to * C#";
            foreach (var tokens in text4.Split("(*)"))
                Console.WriteLine(tokens);

        }
           
    }
}

Here is the output of the script above:

Hello
welcome to
C#
With delimiters =========
Hello*welcome to*C#

In the scrip above, the String.split() function has successfully split the string. However, using (“*”) as a delimiter did not split the string, which shows that unlike Regex.Split() function, the String.split() function cannot be used to split a string including delimiters.

Final Verdict

If you have simple splitting tasks that involve splitting a string using simple delimiters such as commas, asterisks, etc, use String.Split() function. For complex string splitting involving multiple patterns, use Regex.Split(). Furthermore, if you need to include delimiters in the split string, use Regex.Split() since String.split() doesn’t include delimiters in the split string.

Regular Expressions vs IndexOf()

The String.indexOf() function in C# returns the zero-based index for the first character or substring within an input string. The Regex.Match() can also return the index of the first occurrence of a character or a substring within an input string. In this section, you will see both of the ways.

String.indexOf()

Let’s first see how the String.indexOf() function returns the index of the first occurrence of a character or string.

using System;
using System.Text.RegularExpressions;

namespace RegexCodes
{
    class Program
    {
        static void Main(string[] args)
        {
 
            String text = "Welcome to CSharp";
            int index = text.IndexOf("a");
            Console.WriteLine(index);

        }
           
    }
}

The above script returns the index of the first occurrence of the character “a” which is 14 as shown in the output below:
14
Let’s see another example of the indexOf() function where we print the index of the first occurrence of any digit. To do so, we need to pass an array of digits from 1 to 9 to the indexOfAny() function.

namespace RegexCodes
{
    class Program
    {
        static void Main(string[] args)
        {
 
            String text = "Welcome to CSharp 2020";
            int index = text.IndexOfAny("0123456789".ToCharArray());
            Console.WriteLine(index);

        }
           
    }
}

Here is the output of the script above:

18

Regex.Match()

In this section, you will see how Regex.Match() function is used to return the index of the first occurrence of the matched character.

using System;
using System.Text.RegularExpressions;

namespace RegexCodes
{
    class Program
    {
        static void Main(string[] args)
        {
 
            String text = "Welcome to CSharp";
            int index = Regex.Match(text, "a").Index;
            Console.WriteLine(index);

        }
           
    }
}

Here is the output.

14

Finally, you can again use Reges.Match() function to return the first index of any of the digits. To do so, you can use “\d” Regex expression as shown below:

using System;
using System.Text.RegularExpressions;

namespace RegexCodes
{
    class Program
    {
        static void Main(string[] args)
        {
 
            String text = "Welcome to CSharp 2020";
            int index = Regex.Match(text, @"\d").Index;
            Console.WriteLine(index);

        }
           
    }
}

18

Final Verdict

If you want to get the index of a single literal word or character such as digit “9”, or character “a”, you should C# String.indexOf() function. However, if you have a complex pattern to match involving multiple characters in the form of variables such as all digits, all words, or all special characters, use Regex.Match() function.

Regular Expressions vs find()

The find() function in C# is an array function that returns the items in an array that matches certain criteria. The same function can be performed by Regex.Match() or Regex.Matches() function. Let’s see examples of both.

Array.find()

The Array.find() function is applicable to an array. The following script uses the find() function to return the word in the input string that starts with “20”. You can see that the string has to be first converted into an array of words before the find() function operates on it.

using System;
using System.Text.RegularExpressions;

namespace RegexCodes
{
    class Program
    {
        static void Main(string[] args)
        {

            string [] text = "Welcome to CSharp 2020 and 3050".Split();
            var result = Array.Find(text, x =>; x.StartsWith("20"));
            Console.WriteLine(result);

        }
           
    }
}

Here is the output:

2020

Regex.Matches()

Let’s now use Regex.Matches() function to return all the words in the input string that start with a digit.

using System;
using System.Text.RegularExpressions;

namespace RegexCodes
{
    class Program
    {
        static void Main(string[] args)
        {

            string text = "Welcome to CSharp 2020 and 3050";
            var result = Regex.Matches(text, @"(\d+)");
            foreach(var word in result)
            Console.WriteLine(word.ToString());
        }
           
    }
}

Here is the output of the script above.

2020
3050

Final Verdict

In order to find words with a text, Regex.Match() or Regex.Matches() is preferred over the Array.find() function for two reasons. With Regex, you do not need to split the input string into an array of words. And secondly, with Regex, you can easily perform generic matches such as any digit or any words. With find(), you have to specify literal values to search.