Separate items from a string using Regex

1

I need to separate the items from a string into an array using C # and Regex, could they help me?

The string is as follows: required|email|min:2|max:255

There are some rules I wanted to fit:

  • Separate the main items delimited by the | toolbar.
  • Ignore if there is a slash at the end of the string, example required|email| .
  • Separate items that have a value, example min:2 and max:255 .
asked by anonymous 15.06.2016 / 21:51

1 answer

1

I recommend using Split normal, it is usually more efficient than Regex.

If all values have to be separated, just give Split for the two characters and use the option to ignore empty divisions: Split(new char[] { ':', '|' }, StringSplitOptions.RemoveEmptyEntries) .

If the values separated by " : " need to be together, the solution complicates a bit. One of the problems is that there is no Array or List of different types in C# , so an alternative would be List of Array :

var texto = "required|email|min:2|max:255";

var itensSeparados = texto.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries)
    .Select(x => x.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries))
    .ToList();

foreach (var item in itensSeparados)
{
    if (item.Length == 1)
        ; // Item único
    else
        ; // Itens separados por ":"
}
    
15.06.2016 / 22:24