C#idiomatic C#
divide-up-stringsstandard/base-types

Core library

Extract substrings from a string

Learn about different techniques to extract parts of a string, including String.Split, regular expressions, String.Substring, and the range operator.

  • page standard/base-types/divide-up-strings
  • updated 03/20/2026

This article covers some different techniques for extracting parts of a string.

String.Split method

System.String.Split provides a handful of overloads to help you break up a string into a group of substrings based on one or more delimiting characters that you specify. You can choose to limit the total number of substrings in the final result, trim white-space characters from substrings, or exclude empty substrings.

The following examples show three different overloads of String.Split(). The first example calls the System.String.Split(System.Char[]) overload without passing any separator characters. When you don't specify any delimiting characters, String.Split() uses default delimiters, which are white-space characters, to split up the string.

sample · csharpdocs/standard/base-types/snippets/parse-strings/csharp/intro.cs1

csharp
using System;

class Intro
{
    public static void Intro1()
    {
        //<snippet1>
        string s = "You win some. You lose some.";

        string[] subs = s.Split();

        foreach (string sub in subs)
        {
            Console.WriteLine($"Substring: {sub}");
        }

        // This example produces the following output:
        //
        // Substring: You
        // Substring: win
        // Substring: some.
        // Substring: You
        // Substring: lose
        // Substring: some.
        //</snippet1>
    }

    public static void Intro2()
    {
        //<snippet2>
        string s = "You win some. You lose some.";

        string[] subs = s.Split(' ', '.');

        foreach (string sub in subs)
        {
            Console.WriteLine($"Substring: {sub}");
        }

        // This example produces the following output:
        //
        // Substring: You
        // Substring: win
        // Substring: some
        // Substring:
        // Substring: You
        // Substring: lose
        // Substring: some
        // Substring:
        //</snippet2>
    }

    public static void Intro3()
    {
        //<snippet3>
        string s = "You win some. You lose some.";
        char[] separators = new char[] { ' ', '.' };

        string[] subs = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);

        foreach (string sub in subs)
        {
            Console.WriteLine($"Substring: {sub}");
        }

        // This example produces the following output:
        //
        // Substring: You
        // Substring: win
        // Substring: some
        // Substring: You
        // Substring: lose
        // Substring: some
        //</snippet3>
    }
}

sample · vbdocs/standard/base-types/snippets/parse-strings/vb/intro.vb1

vb
Module IntroExamples

    Sub Intro1()
        '<snippet1>
        Dim s As String = "You win some. You lose some."
        Dim subs As String() = s.Split()

        For Each substring As String In subs
            Console.WriteLine("Substring: {0}", substring)
        Next

        ' This example produces the following output:
        '
        ' Substring: You
        ' Substring: win
        ' Substring: some.
        ' Substring: You
        ' Substring: lose
        ' Substring: some.
        '</snippet1>
    End Sub

    Sub Intro2()
        '<snippet2>
        Dim s As String = "You win some. You lose some."
        Dim subs As String() = s.Split(" "c, "."c)

        For Each substring As String In subs
            Console.WriteLine("Substring: {0}", substring)
        Next

        ' This example produces the following output:
        '
        ' Substring: You
        ' Substring: win
        ' Substring: some
        ' Substring:
        ' Substring: You
        ' Substring: lose
        ' Substring: some
        ' Substring:
        '</snippet2>
    End Sub

    Sub Intro3()
        '<snippet3>
        Dim s As String = "You win some. You lose some."
        Dim separators As Char() = New Char() {" "c, "."c}
        Dim subs As String() = s.Split(separators, StringSplitOptions.RemoveEmptyEntries)

        For Each substring As String In subs
            Console.WriteLine("Substring: {0}", substring)
        Next

        ' This example produces the following output:
        '
        ' Substring: You
        ' Substring: win
        ' Substring: some
        ' Substring: You
        ' Substring: lose
        ' Substring: some
        '</snippet3>
    End Sub
End Module

As you can see, the period characters (.) are included in two of the substrings. If you want to exclude the period characters, you can add the period character as an additional delimiting character. The next example shows how to do this.

sample · csharpdocs/standard/base-types/snippets/parse-strings/csharp/intro.cs2

csharp
using System;

class Intro
{
    public static void Intro1()
    {
        //<snippet1>
        string s = "You win some. You lose some.";

        string[] subs = s.Split();

        foreach (string sub in subs)
        {
            Console.WriteLine($"Substring: {sub}");
        }

        // This example produces the following output:
        //
        // Substring: You
        // Substring: win
        // Substring: some.
        // Substring: You
        // Substring: lose
        // Substring: some.
        //</snippet1>
    }

    public static void Intro2()
    {
        //<snippet2>
        string s = "You win some. You lose some.";

        string[] subs = s.Split(' ', '.');

        foreach (string sub in subs)
        {
            Console.WriteLine($"Substring: {sub}");
        }

        // This example produces the following output:
        //
        // Substring: You
        // Substring: win
        // Substring: some
        // Substring:
        // Substring: You
        // Substring: lose
        // Substring: some
        // Substring:
        //</snippet2>
    }

    public static void Intro3()
    {
        //<snippet3>
        string s = "You win some. You lose some.";
        char[] separators = new char[] { ' ', '.' };

        string[] subs = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);

        foreach (string sub in subs)
        {
            Console.WriteLine($"Substring: {sub}");
        }

        // This example produces the following output:
        //
        // Substring: You
        // Substring: win
        // Substring: some
        // Substring: You
        // Substring: lose
        // Substring: some
        //</snippet3>
    }
}

sample · vbdocs/standard/base-types/snippets/parse-strings/vb/intro.vb2

vb
Module IntroExamples

    Sub Intro1()
        '<snippet1>
        Dim s As String = "You win some. You lose some."
        Dim subs As String() = s.Split()

        For Each substring As String In subs
            Console.WriteLine("Substring: {0}", substring)
        Next

        ' This example produces the following output:
        '
        ' Substring: You
        ' Substring: win
        ' Substring: some.
        ' Substring: You
        ' Substring: lose
        ' Substring: some.
        '</snippet1>
    End Sub

    Sub Intro2()
        '<snippet2>
        Dim s As String = "You win some. You lose some."
        Dim subs As String() = s.Split(" "c, "."c)

        For Each substring As String In subs
            Console.WriteLine("Substring: {0}", substring)
        Next

        ' This example produces the following output:
        '
        ' Substring: You
        ' Substring: win
        ' Substring: some
        ' Substring:
        ' Substring: You
        ' Substring: lose
        ' Substring: some
        ' Substring:
        '</snippet2>
    End Sub

    Sub Intro3()
        '<snippet3>
        Dim s As String = "You win some. You lose some."
        Dim separators As Char() = New Char() {" "c, "."c}
        Dim subs As String() = s.Split(separators, StringSplitOptions.RemoveEmptyEntries)

        For Each substring As String In subs
            Console.WriteLine("Substring: {0}", substring)
        Next

        ' This example produces the following output:
        '
        ' Substring: You
        ' Substring: win
        ' Substring: some
        ' Substring: You
        ' Substring: lose
        ' Substring: some
        '</snippet3>
    End Sub
End Module

The periods are gone from the substrings, but now two extra empty substrings have been included. These empty substring represent the substring between the word and the period that follows it. To omit empty substrings from the resulting array, you can call the System.String.Split(System.Char[],System.StringSplitOptions) overload and specify System.StringSplitOptions.RemoveEmptyEntries for the options parameter.

sample · csharpdocs/standard/base-types/snippets/parse-strings/csharp/intro.cs3

csharp
using System;

class Intro
{
    public static void Intro1()
    {
        //<snippet1>
        string s = "You win some. You lose some.";

        string[] subs = s.Split();

        foreach (string sub in subs)
        {
            Console.WriteLine($"Substring: {sub}");
        }

        // This example produces the following output:
        //
        // Substring: You
        // Substring: win
        // Substring: some.
        // Substring: You
        // Substring: lose
        // Substring: some.
        //</snippet1>
    }

    public static void Intro2()
    {
        //<snippet2>
        string s = "You win some. You lose some.";

        string[] subs = s.Split(' ', '.');

        foreach (string sub in subs)
        {
            Console.WriteLine($"Substring: {sub}");
        }

        // This example produces the following output:
        //
        // Substring: You
        // Substring: win
        // Substring: some
        // Substring:
        // Substring: You
        // Substring: lose
        // Substring: some
        // Substring:
        //</snippet2>
    }

    public static void Intro3()
    {
        //<snippet3>
        string s = "You win some. You lose some.";
        char[] separators = new char[] { ' ', '.' };

        string[] subs = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);

        foreach (string sub in subs)
        {
            Console.WriteLine($"Substring: {sub}");
        }

        // This example produces the following output:
        //
        // Substring: You
        // Substring: win
        // Substring: some
        // Substring: You
        // Substring: lose
        // Substring: some
        //</snippet3>
    }
}

sample · vbdocs/standard/base-types/snippets/parse-strings/vb/intro.vb3

vb
Module IntroExamples

    Sub Intro1()
        '<snippet1>
        Dim s As String = "You win some. You lose some."
        Dim subs As String() = s.Split()

        For Each substring As String In subs
            Console.WriteLine("Substring: {0}", substring)
        Next

        ' This example produces the following output:
        '
        ' Substring: You
        ' Substring: win
        ' Substring: some.
        ' Substring: You
        ' Substring: lose
        ' Substring: some.
        '</snippet1>
    End Sub

    Sub Intro2()
        '<snippet2>
        Dim s As String = "You win some. You lose some."
        Dim subs As String() = s.Split(" "c, "."c)

        For Each substring As String In subs
            Console.WriteLine("Substring: {0}", substring)
        Next

        ' This example produces the following output:
        '
        ' Substring: You
        ' Substring: win
        ' Substring: some
        ' Substring:
        ' Substring: You
        ' Substring: lose
        ' Substring: some
        ' Substring:
        '</snippet2>
    End Sub

    Sub Intro3()
        '<snippet3>
        Dim s As String = "You win some. You lose some."
        Dim separators As Char() = New Char() {" "c, "."c}
        Dim subs As String() = s.Split(separators, StringSplitOptions.RemoveEmptyEntries)

        For Each substring As String In subs
            Console.WriteLine("Substring: {0}", substring)
        Next

        ' This example produces the following output:
        '
        ' Substring: You
        ' Substring: win
        ' Substring: some
        ' Substring: You
        ' Substring: lose
        ' Substring: some
        '</snippet3>
    End Sub
End Module

Regular expressions

If your string conforms to a fixed pattern, you can use a regular expression to extract and handle its elements. For example, if strings take the form "number operand number", you can use a regular expression to extract and handle the string's elements. Here's an example:

sample · csharpdocs/standard/base-types/snippets/parse-strings/csharp/regex.cs1

csharp
using System;

public class RegExExamples
{
    public static void Example1()
    {
        // <Snippet1>
        String[] expressions = { "16 + 21", "31 * 3", "28 / 3",
                               "42 - 18", "12 * 7",
                               "2, 4, 6, 8" };
        String pattern = @"(\d+)\s+([-+*/])\s+(\d+)";

        foreach (string expression in expressions)
        {
            foreach (System.Text.RegularExpressions.Match m in
            System.Text.RegularExpressions.Regex.Matches(expression, pattern))
            {
                int value1 = Int32.Parse(m.Groups[1].Value);
                int value2 = Int32.Parse(m.Groups[3].Value);
                switch (m.Groups[2].Value)
                {
                    case "+":
                        Console.WriteLine($"{m.Value} = {value1 + value2}");
                        break;
                    case "-":
                        Console.WriteLine($"{m.Value} = {value1 - value2}");
                        break;
                    case "*":
                        Console.WriteLine($"{m.Value} = {value1 * value2}");
                        break;
                    case "/":
                        Console.WriteLine($"{m.Value} = {value1 / value2:N2}");
                        break;
                }
            }
        }

        // The example displays the following output:
        //       16 + 21 = 37
        //       31 * 3 = 93
        //       28 / 3 = 9.33
        //       42 - 18 = 24
        //       12 * 7 = 84
        // </Snippet1>
    }

    public static void Example2()
    {
        // <Snippet2>
        String input = "[This is captured\ntext.]\n\n[\n" +
                       "[This is more captured text.]\n]\n" +
                       "[Some more captured text:\n   Option1" +
                       "\n   Option2][Terse text.]";
        String pattern = @"\[([^\[\]]+)\]";
        int ctr = 0;

        foreach (System.Text.RegularExpressions.Match m in
           System.Text.RegularExpressions.Regex.Matches(input, pattern))
        {
            Console.WriteLine($"{++ctr}: {m.Groups[1].Value}");
        }

        // The example displays the following output:
        //       1: This is captured
        //       text.
        //       2: This is more captured text.
        //       3: Some more captured text:
        //          Option1
        //          Option2
        //       4: Terse text.
        // </Snippet2>
    }

    public static void Example3()
    {
        // <Snippet3>
        String input = "abacus -- alabaster - * - atrium -+- " +
                       "any -*- actual - + - armoire - - alarm";
        String pattern = @"\s-\s?[+*]?\s?-\s";
        String[] elements = System.Text.RegularExpressions.Regex.Split(input, pattern);

        foreach (string element in elements)
            Console.WriteLine(element);

        // The example displays the following output:
        //       abacus
        //       alabaster
        //       atrium
        //       any
        //       actual
        //       armoire
        //       alarm
        // </Snippet3>
    }
}

sample · vbdocs/standard/base-types/snippets/parse-strings/vb/regex.vb1

vb
' Visual Basic .NET Document
Option Strict On

Imports System.Text.RegularExpressions

Module RegExExamples
    Public Sub Example1()
        ' <Snippet1>
        Dim expressions() As String = {"16 + 21", "31 * 3", "28 / 3",
                                      "42 - 18", "12 * 7",
                                      "2, 4, 6, 8"}

        Dim pattern As String = "(\d+)\s+([-+*/])\s+(\d+)"
        For Each expression In expressions
            For Each m As Match In Regex.Matches(expression, pattern)
                Dim value1 As Integer = Int32.Parse(m.Groups(1).Value)
                Dim value2 As Integer = Int32.Parse(m.Groups(3).Value)
                Select Case m.Groups(2).Value
                    Case "+"
                        Console.WriteLine("{0} = {1}", m.Value, value1 + value2)
                    Case "-"
                        Console.WriteLine("{0} = {1}", m.Value, value1 - value2)
                    Case "*"
                        Console.WriteLine("{0} = {1}", m.Value, value1 * value2)
                    Case "/"
                        Console.WriteLine("{0} = {1:N2}", m.Value, value1 / value2)
                End Select
            Next
        Next

        ' The example displays the following output:
        '       16 + 21 = 37
        '       31 * 3 = 93
        '       28 / 3 = 9.33
        '       42 - 18 = 24
        '       12 * 7 = 84
        ' </Snippet1>
    End Sub

    Public Sub Example2()
        ' <Snippet2>
        Dim input As String = String.Format("[This is captured{0}text.]" +
                                          "{0}{0}[{0}[This is more " +
                                          "captured text.]{0}{0}" +
                                          "[Some more captured text:" +
                                          "{0}   Option1" +
                                          "{0}   Option2][Terse text.]",
                                          vbCrLf)
        Dim pattern As String = "\[([^\[\]]+)\]"
        Dim ctr As Integer = 0
        For Each m As Match In Regex.Matches(input, pattern)
            ctr += 1
            Console.WriteLine("{0}: {1}", ctr, m.Groups(1).Value)
        Next

        ' The example displays the following output:
        '       1: This is captured
        '       text.
        '       2: This is more captured text.
        '       3: Some more captured text:
        '          Option1
        '          Option2
        '       4: Terse text.
        ' </Snippet2>
    End Sub


    Public Sub Example3()
        ' <Snippet3>
        Dim input As String = "abacus -- alabaster - * - atrium -+- " +
                            "any -*- actual - + - armoire - - alarm"
        Dim pattern As String = "\s-\s?[+*]?\s?-\s"
        Dim elements() As String = Regex.Split(input, pattern)
        For Each element In elements
            Console.WriteLine(element)
        Next

        ' The example displays the following output:
        '       abacus
        '       alabaster
        '       atrium
        '       any
        '       actual
        '       armoire
        '       alarm
        ' </Snippet3>
    End Sub
End Module

The regular expression pattern (\d+)\s+([-+*/])\s+(\d+) is defined like this:

Pattern Description
(\d+) Match one or more decimal digits. This is the first capturing group.
\s+ Match one or more white-space characters.
([-+*/]) Match an arithmetic operator sign (+, -, *, or /). This is the second capturing group.
\s+ Match one or more white-space characters.
(\d+) Match one or more decimal digits. This is the third capturing group.

You can also use a regular expression to extract substrings from a string based on a pattern rather than a fixed set of characters. This is a common scenario when either of these conditions occurs:

  • One or more of the delimiter characters does not always serve as a delimiter in the System.String instance.

  • The sequence and number of delimiter characters is variable or unknown.

For example, the System.String.Split method cannot be used to split the following string, because the number of \n (newline) characters is variable, and they don't always serve as delimiters.

text
[This is captured\ntext.]\n\n[\n[This is more captured text.]\n]
\n[Some more captured text:\n   Option1\n   Option2][Terse text.]

A regular expression can split this string easily, as the following example shows.

sample · csharpdocs/standard/base-types/snippets/parse-strings/csharp/regex.cs2

csharp
using System;

public class RegExExamples
{
    public static void Example1()
    {
        // <Snippet1>
        String[] expressions = { "16 + 21", "31 * 3", "28 / 3",
                               "42 - 18", "12 * 7",
                               "2, 4, 6, 8" };
        String pattern = @"(\d+)\s+([-+*/])\s+(\d+)";

        foreach (string expression in expressions)
        {
            foreach (System.Text.RegularExpressions.Match m in
            System.Text.RegularExpressions.Regex.Matches(expression, pattern))
            {
                int value1 = Int32.Parse(m.Groups[1].Value);
                int value2 = Int32.Parse(m.Groups[3].Value);
                switch (m.Groups[2].Value)
                {
                    case "+":
                        Console.WriteLine($"{m.Value} = {value1 + value2}");
                        break;
                    case "-":
                        Console.WriteLine($"{m.Value} = {value1 - value2}");
                        break;
                    case "*":
                        Console.WriteLine($"{m.Value} = {value1 * value2}");
                        break;
                    case "/":
                        Console.WriteLine($"{m.Value} = {value1 / value2:N2}");
                        break;
                }
            }
        }

        // The example displays the following output:
        //       16 + 21 = 37
        //       31 * 3 = 93
        //       28 / 3 = 9.33
        //       42 - 18 = 24
        //       12 * 7 = 84
        // </Snippet1>
    }

    public static void Example2()
    {
        // <Snippet2>
        String input = "[This is captured\ntext.]\n\n[\n" +
                       "[This is more captured text.]\n]\n" +
                       "[Some more captured text:\n   Option1" +
                       "\n   Option2][Terse text.]";
        String pattern = @"\[([^\[\]]+)\]";
        int ctr = 0;

        foreach (System.Text.RegularExpressions.Match m in
           System.Text.RegularExpressions.Regex.Matches(input, pattern))
        {
            Console.WriteLine($"{++ctr}: {m.Groups[1].Value}");
        }

        // The example displays the following output:
        //       1: This is captured
        //       text.
        //       2: This is more captured text.
        //       3: Some more captured text:
        //          Option1
        //          Option2
        //       4: Terse text.
        // </Snippet2>
    }

    public static void Example3()
    {
        // <Snippet3>
        String input = "abacus -- alabaster - * - atrium -+- " +
                       "any -*- actual - + - armoire - - alarm";
        String pattern = @"\s-\s?[+*]?\s?-\s";
        String[] elements = System.Text.RegularExpressions.Regex.Split(input, pattern);

        foreach (string element in elements)
            Console.WriteLine(element);

        // The example displays the following output:
        //       abacus
        //       alabaster
        //       atrium
        //       any
        //       actual
        //       armoire
        //       alarm
        // </Snippet3>
    }
}

sample · vbdocs/standard/base-types/snippets/parse-strings/vb/regex.vb2

vb
' Visual Basic .NET Document
Option Strict On

Imports System.Text.RegularExpressions

Module RegExExamples
    Public Sub Example1()
        ' <Snippet1>
        Dim expressions() As String = {"16 + 21", "31 * 3", "28 / 3",
                                      "42 - 18", "12 * 7",
                                      "2, 4, 6, 8"}

        Dim pattern As String = "(\d+)\s+([-+*/])\s+(\d+)"
        For Each expression In expressions
            For Each m As Match In Regex.Matches(expression, pattern)
                Dim value1 As Integer = Int32.Parse(m.Groups(1).Value)
                Dim value2 As Integer = Int32.Parse(m.Groups(3).Value)
                Select Case m.Groups(2).Value
                    Case "+"
                        Console.WriteLine("{0} = {1}", m.Value, value1 + value2)
                    Case "-"
                        Console.WriteLine("{0} = {1}", m.Value, value1 - value2)
                    Case "*"
                        Console.WriteLine("{0} = {1}", m.Value, value1 * value2)
                    Case "/"
                        Console.WriteLine("{0} = {1:N2}", m.Value, value1 / value2)
                End Select
            Next
        Next

        ' The example displays the following output:
        '       16 + 21 = 37
        '       31 * 3 = 93
        '       28 / 3 = 9.33
        '       42 - 18 = 24
        '       12 * 7 = 84
        ' </Snippet1>
    End Sub

    Public Sub Example2()
        ' <Snippet2>
        Dim input As String = String.Format("[This is captured{0}text.]" +
                                          "{0}{0}[{0}[This is more " +
                                          "captured text.]{0}{0}" +
                                          "[Some more captured text:" +
                                          "{0}   Option1" +
                                          "{0}   Option2][Terse text.]",
                                          vbCrLf)
        Dim pattern As String = "\[([^\[\]]+)\]"
        Dim ctr As Integer = 0
        For Each m As Match In Regex.Matches(input, pattern)
            ctr += 1
            Console.WriteLine("{0}: {1}", ctr, m.Groups(1).Value)
        Next

        ' The example displays the following output:
        '       1: This is captured
        '       text.
        '       2: This is more captured text.
        '       3: Some more captured text:
        '          Option1
        '          Option2
        '       4: Terse text.
        ' </Snippet2>
    End Sub


    Public Sub Example3()
        ' <Snippet3>
        Dim input As String = "abacus -- alabaster - * - atrium -+- " +
                            "any -*- actual - + - armoire - - alarm"
        Dim pattern As String = "\s-\s?[+*]?\s?-\s"
        Dim elements() As String = Regex.Split(input, pattern)
        For Each element In elements
            Console.WriteLine(element)
        Next

        ' The example displays the following output:
        '       abacus
        '       alabaster
        '       atrium
        '       any
        '       actual
        '       armoire
        '       alarm
        ' </Snippet3>
    End Sub
End Module

The regular expression pattern \[([^\[\]]+)\] is defined like this:

Pattern Description
\[ Match an opening bracket.
([^\[\]]+) Match any character that is not an opening or a closing bracket one or more times. This is the first capturing group.
\] Match a closing bracket.

The System.Text.RegularExpressions.Regex.Split method is almost identical to System.String.Split, except that it splits a string based on a regular expression pattern instead of a fixed character set. For example, the following example uses the System.Text.RegularExpressions.Regex.Split method to split a string that contains substrings delimited by various combinations of hyphens and other characters.

sample · csharpdocs/standard/base-types/snippets/parse-strings/csharp/regex.cs3

csharp
using System;

public class RegExExamples
{
    public static void Example1()
    {
        // <Snippet1>
        String[] expressions = { "16 + 21", "31 * 3", "28 / 3",
                               "42 - 18", "12 * 7",
                               "2, 4, 6, 8" };
        String pattern = @"(\d+)\s+([-+*/])\s+(\d+)";

        foreach (string expression in expressions)
        {
            foreach (System.Text.RegularExpressions.Match m in
            System.Text.RegularExpressions.Regex.Matches(expression, pattern))
            {
                int value1 = Int32.Parse(m.Groups[1].Value);
                int value2 = Int32.Parse(m.Groups[3].Value);
                switch (m.Groups[2].Value)
                {
                    case "+":
                        Console.WriteLine($"{m.Value} = {value1 + value2}");
                        break;
                    case "-":
                        Console.WriteLine($"{m.Value} = {value1 - value2}");
                        break;
                    case "*":
                        Console.WriteLine($"{m.Value} = {value1 * value2}");
                        break;
                    case "/":
                        Console.WriteLine($"{m.Value} = {value1 / value2:N2}");
                        break;
                }
            }
        }

        // The example displays the following output:
        //       16 + 21 = 37
        //       31 * 3 = 93
        //       28 / 3 = 9.33
        //       42 - 18 = 24
        //       12 * 7 = 84
        // </Snippet1>
    }

    public static void Example2()
    {
        // <Snippet2>
        String input = "[This is captured\ntext.]\n\n[\n" +
                       "[This is more captured text.]\n]\n" +
                       "[Some more captured text:\n   Option1" +
                       "\n   Option2][Terse text.]";
        String pattern = @"\[([^\[\]]+)\]";
        int ctr = 0;

        foreach (System.Text.RegularExpressions.Match m in
           System.Text.RegularExpressions.Regex.Matches(input, pattern))
        {
            Console.WriteLine($"{++ctr}: {m.Groups[1].Value}");
        }

        // The example displays the following output:
        //       1: This is captured
        //       text.
        //       2: This is more captured text.
        //       3: Some more captured text:
        //          Option1
        //          Option2
        //       4: Terse text.
        // </Snippet2>
    }

    public static void Example3()
    {
        // <Snippet3>
        String input = "abacus -- alabaster - * - atrium -+- " +
                       "any -*- actual - + - armoire - - alarm";
        String pattern = @"\s-\s?[+*]?\s?-\s";
        String[] elements = System.Text.RegularExpressions.Regex.Split(input, pattern);

        foreach (string element in elements)
            Console.WriteLine(element);

        // The example displays the following output:
        //       abacus
        //       alabaster
        //       atrium
        //       any
        //       actual
        //       armoire
        //       alarm
        // </Snippet3>
    }
}

sample · vbdocs/standard/base-types/snippets/parse-strings/vb/regex.vb3

vb
' Visual Basic .NET Document
Option Strict On

Imports System.Text.RegularExpressions

Module RegExExamples
    Public Sub Example1()
        ' <Snippet1>
        Dim expressions() As String = {"16 + 21", "31 * 3", "28 / 3",
                                      "42 - 18", "12 * 7",
                                      "2, 4, 6, 8"}

        Dim pattern As String = "(\d+)\s+([-+*/])\s+(\d+)"
        For Each expression In expressions
            For Each m As Match In Regex.Matches(expression, pattern)
                Dim value1 As Integer = Int32.Parse(m.Groups(1).Value)
                Dim value2 As Integer = Int32.Parse(m.Groups(3).Value)
                Select Case m.Groups(2).Value
                    Case "+"
                        Console.WriteLine("{0} = {1}", m.Value, value1 + value2)
                    Case "-"
                        Console.WriteLine("{0} = {1}", m.Value, value1 - value2)
                    Case "*"
                        Console.WriteLine("{0} = {1}", m.Value, value1 * value2)
                    Case "/"
                        Console.WriteLine("{0} = {1:N2}", m.Value, value1 / value2)
                End Select
            Next
        Next

        ' The example displays the following output:
        '       16 + 21 = 37
        '       31 * 3 = 93
        '       28 / 3 = 9.33
        '       42 - 18 = 24
        '       12 * 7 = 84
        ' </Snippet1>
    End Sub

    Public Sub Example2()
        ' <Snippet2>
        Dim input As String = String.Format("[This is captured{0}text.]" +
                                          "{0}{0}[{0}[This is more " +
                                          "captured text.]{0}{0}" +
                                          "[Some more captured text:" +
                                          "{0}   Option1" +
                                          "{0}   Option2][Terse text.]",
                                          vbCrLf)
        Dim pattern As String = "\[([^\[\]]+)\]"
        Dim ctr As Integer = 0
        For Each m As Match In Regex.Matches(input, pattern)
            ctr += 1
            Console.WriteLine("{0}: {1}", ctr, m.Groups(1).Value)
        Next

        ' The example displays the following output:
        '       1: This is captured
        '       text.
        '       2: This is more captured text.
        '       3: Some more captured text:
        '          Option1
        '          Option2
        '       4: Terse text.
        ' </Snippet2>
    End Sub


    Public Sub Example3()
        ' <Snippet3>
        Dim input As String = "abacus -- alabaster - * - atrium -+- " +
                            "any -*- actual - + - armoire - - alarm"
        Dim pattern As String = "\s-\s?[+*]?\s?-\s"
        Dim elements() As String = Regex.Split(input, pattern)
        For Each element In elements
            Console.WriteLine(element)
        Next

        ' The example displays the following output:
        '       abacus
        '       alabaster
        '       atrium
        '       any
        '       actual
        '       armoire
        '       alarm
        ' </Snippet3>
    End Sub
End Module

The regular expression pattern \s-\s?[+*]?\s?-\s is defined like this:

Pattern Description
\s- Match a white-space character followed by a hyphen.
\s? Match zero or one white-space character.
[+*]? Match zero or one occurrence of either the + or * character.
\s? Match zero or one white-space character.
-\s Match a hyphen followed by a white-space character.

String.IndexOf and String.Substring methods

If you aren't interested in all of the substrings in a string, you might prefer to work with one of the string comparison methods that returns the index at which the match begins. You can then call the System.String.Substring method to extract the substring that you want. The string comparison methods include:

  • System.String.IndexOf, which returns the zero-based index of the first occurrence of a character or string in a string instance.

  • System.String.IndexOfAny, which returns the zero-based index in the current string instance of the first occurrence of any character in a character array.

  • System.String.LastIndexOf, which returns the zero-based index of the last occurrence of a character or string in a string instance.

  • System.String.LastIndexOfAny, which returns a zero-based index in the current string instance of the last occurrence of any character in a character array.

The following example uses the System.String.IndexOf method to find the periods in a string. It then uses the System.String.Substring method to return full sentences.

sample · csharpdocs/standard/base-types/snippets/parse-strings/csharp/indexof.cs1

csharp
using System;
using System.Collections.Generic;

public class IndexOfExample
{
    public static void Example1()
    {
        // <Snippet1>
        String s = "This is the first sentence in a string. " +
                       "More sentences will follow. For example, " +
                       "this is the third sentence. This is the " +
                       "fourth. And this is the fifth and final " +
                       "sentence.";
        var sentences = new List<String>();
        int start = 0;
        int position;

        // Extract sentences from the string.
        do
        {
            position = s.IndexOf('.', start);
            if (position >= 0)
            {
                sentences.Add(s.Substring(start, position - start + 1).Trim());
                start = position + 1;
            }
        } while (position > 0);

        // Display the sentences.
        foreach (var sentence in sentences)
            Console.WriteLine(sentence);

        // The example displays the following output:
        //       This is the first sentence in a string.
        //       More sentences will follow.
        //       For example, this is the third sentence.
        //       This is the fourth.
        //       And this is the fifth and final sentence.
        // </Snippet1>
    }
}

sample · vbdocs/standard/base-types/snippets/parse-strings/vb/indexof.vb1

vb
' Visual Basic .NET Document
Option Strict On

Module Example
    Public Sub Example1()
        ' <Snippet1>
        Dim input As String = "This is the first sentence in a string. " +
                            "More sentences will follow. For example, " +
                            "this is the third sentence. This is the " +
                            "fourth. And this is the fifth and final " +
                            "sentence."
        Dim sentences As New List(Of String)
        Dim start As Integer = 0
        Dim position As Integer

        ' Extract sentences from the string.
        Do
            position = input.IndexOf("."c, start)
            If position >= 0 Then
                sentences.Add(input.Substring(start, position - start + 1).Trim())
                start = position + 1
            End If
        Loop While position > 0

        ' Display the sentences.
        For Each sentence In sentences
            Console.WriteLine(sentence)
        Next
    End Sub

    ' The example displays the following output:
    '       This is the first sentence in a string.
    '       More sentences will follow.
    '       For example, this is the third sentence.
    '       This is the fourth.
    '       And this is the fifth and final sentence.
    ' </Snippet1>
End Module

Ranges and indices

The C# range operator .. and the index-from-end operator ^ let you extract substrings using a concise syntax. You can apply these operators directly to strings without calling System.String.Substring.

The following example shows several ways to extract parts of a string using ranges:

sample · csharpdocs/standard/base-types/snippets/parse-strings/csharp/range.cssnippet1

csharp
public class RangeExamples
{
    public static void Example1()
    {
        // <snippet1>
        string str = "Hello, World!";

        // Get the first 5 characters.
        string hello = str[..5];
        Console.WriteLine(hello);
        // Output: Hello

        // Get the last 6 characters.
        string world = str[^6..];
        Console.WriteLine(world);
        // Output: World!

        // Get characters from index 7 through 11 (exclusive of 12).
        string substr = str[7..12];
        Console.WriteLine(substr);
        // Output: World
        // </snippet1>
    }

    public static void Example2()
    {
        // <snippet2>
        string filePath = "C:\\Users\\user1\\bin\\fileA.cs";

        // Remove the last 3 characters (.cs extension).
        string trimmedPath = filePath[..^3];
        Console.WriteLine(trimmedPath);
        // Output: C:\Users\user1\bin\fileA
        // </snippet2>
    }
}

The next example uses the index-from-end operator to remove a file extension (the last three characters) from a path:

sample · csharpdocs/standard/base-types/snippets/parse-strings/csharp/range.cssnippet2

csharp
public class RangeExamples
{
    public static void Example1()
    {
        // <snippet1>
        string str = "Hello, World!";

        // Get the first 5 characters.
        string hello = str[..5];
        Console.WriteLine(hello);
        // Output: Hello

        // Get the last 6 characters.
        string world = str[^6..];
        Console.WriteLine(world);
        // Output: World!

        // Get characters from index 7 through 11 (exclusive of 12).
        string substr = str[7..12];
        Console.WriteLine(substr);
        // Output: World
        // </snippet1>
    }

    public static void Example2()
    {
        // <snippet2>
        string filePath = "C:\\Users\\user1\\bin\\fileA.cs";

        // Remove the last 3 characters (.cs extension).
        string trimmedPath = filePath[..^3];
        Console.WriteLine(trimmedPath);
        // Output: C:\Users\user1\bin\fileA
        // </snippet2>
    }
}

See also