Y N
Y N

Reputation: 841

C# working with strings and Regex

I have such a string

|   7   |      2       |39,93 |

and I need to split it into an array where the first element is "7", second "2" and third is "39,93"

I've came up with the following solution

var line     =  "|   7   |      2       |39,93 |";
line = line.Remove(0, 1);
string[] arr = Regex.Replace(line, @"\s+", "").Trim().Split('|');

I wonder if there is a better way to do this.

Upvotes: 1

Views: 61

Answers (2)

Matthew Walton
Matthew Walton

Reputation: 9959

Yes.

var output =
    line.Split("|") // split on the pipes
        .Select(x => x.Trim()) // remove excess whitespace from each item
        .Where(x => !string.IsNullOrEmpty(x)) // remove any empty items
        .ToArray(); // convert to array

Regexes don't really help you very much here. You could do it with a regex, but it'd probably be harder to read. There's a possibility it might be more efficient though. You'd have to test that.

I'm anticipating empty items appearing at the start and end that need to be dropped because of those initial and terminal pipes, but if there are empty elements in the middle that you wanted to keep you'd have to adjust that part.

Upvotes: 1

Habib
Habib

Reputation: 223277

You don't need regex for this, you can do it using String.Split and some LINQ like:

var line = "|   7   |      2       |39,93 |";
var array = line.Split(new[] { '|'}, StringSplitOptions.RemoveEmptyEntries)
            .Select(s => s.Trim()).ToArray();

Upvotes: 8

Related Questions