How to split single string into array of the strings through Regular expression in .net

The Following example shows how to split single string into array of the strings with the help of Regular expression in .net. We can split an input string into an array of substrings at the positions defined by a regular expression match.


In this example we can get the array of the cities from the string ‘1. Delhi 2. Mumbai 3. Sydney 4. Newyork 15. Tokyo 120. Londan’ by split this string with certain match pattern. we are using “\b\d+\.\s” regular expression string pattern.
 
The regular expression pattern \b\d+\.\s is defined as:
\b : Start at a word boundary.
\d+ : Match one or more decimal digits.
\. : Match the decimal point character.
\s : Match a white-space character.
 
and we use Regex.Split(string input,string pattern) method. see this:

[VB]

Private Sub GetArrayOfCities()
     Dim str As String = "1. Delhi 2. Mumbai 3. Sydney 4. Newyork 15. Tokyo 120. Londan"
     Dim regxPattern As String = "\b\d+\.\s"
     Dim ArrCities As String() = Regex.Split(str, regxPattern)
End Sub

[C#]

private void GetArrayOfCities()
        {
            string str = "1. Delhi 2. Mumbai 3. Sydney 4. Newyork 15. Tokyo 120. Londan";
            string regxPattern = "\\b\\d+\\.\\s";
            string[] ArrCities = Regex.Split(str, regxPattern);
        }

You can see value of ArrCities as:
ArrCities[0]=””
ArrCities[1]=”Delhi”
ArrCities[2]=”Mumbai”
ArrCities[3]=”Sydney”
ArrCities[4]=”Newyork”
ArrCities[5]=”Tokyo”
ArrCities[6]=”Londa”

One thought on “How to split single string into array of the strings through Regular expression in .net”

  1. very interesting thing…till now i use String.Split() function for getting data from the string and some time it create very confusionĀ  but Regex.Split function is very useful for splittingĀ  such type of string.

    very thanks

Comments are closed.