RegEx.Split vs. String.Split

RegEx.Split vs. String.Split

The String.Split method has few limitations. For example, it does not support splits on duplicate delimiters such as double pipe (||) characters, double tildes (~~), or double colons (::).

The easiest and most efficient workaround is to use the RegEx.Split method instead. Using RegEx you can escape the specific characters that are part of the pattern:

string[] output  = null;string inputSentence = "I am a developer|| I work on .Net || " +    "The latest framework available is 3.5";//the following line will not workoutput = inputSentence .Split("||".ToCharArray());//use RegEx Split insteadoutput =  System.Text.RegularExpressions.Regex.Split(   inputSentence, System.Text.RegularExpressions.Regex.Escape("||"));

The Escape method replaces the string parameter with an escaped version of the same string, returning a value that can contain regular expression reserved characters (such as the pipe character).

The preceding code passes that escaped expression into the Split method to split the string at the double pipe characters. Note that the method returns a string array just as String.Split does, which makes it a convenient replacement.


Share the Post: