-
Notifications
You must be signed in to change notification settings - Fork 4
StringSplit
Mehdi Mohammadi edited this page Dec 29, 2013
·
1 revision
String.split method in Java accepts RegularExpressions
Regex.Split method in .Net has similar behavior, but there are some differences:
-
[Delimiters] (http://msdn2.microsoft.com/en-us/library/ze12yx1d.aspx#remarksToggle) should be defined as non-capturing groups. '(?:)' rather than '()'
-
It may return an empty string as the last item ?
We replace call to String.split with Helpers.Regex rather than default System.Text.RegularExpressions.Regex class.
This class contains a Split method which hides differences explained above:
public static string[] Split(string input, string pattern)
{
//Replace with non-capturing group
int pIndex = pattern.IndexOf("(");
while (pIndex != -1 && pIndex != pattern.Length - 1)
{
if (pattern[pIndex + 1] != '?')
pattern = pattern.Insert(pIndex + 1, "?:");
pIndex = pattern.IndexOf("(", pIndex + 1);
}
string[] parts = System.Text.RegularExpressions.Regex.Split(input, pattern);
ArrayList list = new ArrayList();
for (int i = 0; i < parts.Length - 1; i++)
list.Add(parts[i]);
if (parts[parts.Length - 1] != "")
list.Add(parts[parts.Length - 1]);
return (string[]) list.ToArray(typeof(string));
}
See also HelperClass if you want to add helper classes to Janett. See also Mapping as for how to map methods to helper classes.