Separate items from a string using Regex

Asked

Viewed 204 times

1

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

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

There are some rules I wanted to suit:

  • Separate main items delimited by the bar |.
  • Ignore if there is a bar at the end of the string, example required|email|.
  • Separate items that have a value, example min:2 and max:255.
  • The items separated by ":" will stay together in the same item or they will be totally separate?

  • Together in the same item.

  • If the items of ":" have to stay together somehow, I think the answer I gave you will not solve. You would have to, for example, create a list of Array, most of which Array would have only one position and those who had more than one position would be of the items separated by ":"... If you really need it, just comment here that I change the answer!

  • Exactly, what I need is something that generates an array where the items that are separated by : are included in another level, where the first string is the key and the second string is the value, example: ["required", ["max", 255], ["min": 6], "email"].

  • Edited response to include a solution to this situation.

1 answer

1


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

If all values have to be separated, just give Split by both 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 little. One of the problems is that there is no Array or List of different types in the C#, then 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 ":"
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.