Wednesday, July 9, 2014

Split a string with multiple space as delimiter or separator (Regex or String.Split)

Given that you have a string that you want to split and the separator is two or more spaces. You can achieve using split() or Regex.
VB.NET
1
2
3
4
5
6
7
8
Dim str As String = "Rule Name:                            WhosThere-176.44.28.203"
Dim whosThereVar As String
Dim whosThereString As String

'using split
whosThereVar = str.Split(New String() {"  "}, StringSplitOptions.RemoveEmptyEntries)(1).Trim()
'using regex
whosThereString = System.Text.RegularExpressions.Regex.Split(str, "\s{2,}")(1)
C#
1
2
3
4
5
string str = "Rule Name:                            WhosThere-176.44.28.203";
//using split
string whosThereVar = str.Split(new string[] { "  " }, StringSplitOptions.RemoveEmptyEntries)[1].Trim();
//using regex
string whosThereString = System.Text.RegularExpressions.Regex.Split(str, @"\s{2,}")[1];

0 comments:

Post a Comment