Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex.Split adding empty strings to result array

Tags:

c#

regex

I have a Regex to split out words operators and brackets in simple logic statements (e.g. "WORD1 & WORD2 | (WORd_3 & !word_4 )". the Regex I've come up with is "(?[A-Za-z0-9_]+)|(?[&!\|()]{1})". Here is a quick test program.


using System; 
using System.Text.RegularExpressions;

namespace ConsoleApplication1 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
        Console.WriteLine("* Test Project *"); 
        string testExpression = "!(LIONV6 | NOT_superCHARGED) &RHD"; 
        string removedSpaces = testExpression.Replace(" ", ""); 
        string[] expectedResults = new string[] { "!", "(", "LIONV6", "|", "NOT_superCHARGED", ")", "&", "RHD" }; 
        string[] splits = Regex.Split(removedSpaces, @"(?[A-Za-z0-9_]+)|(?[&!\|()]{1})");

        Console.WriteLine("Expected\n{0}\nActual\n{1}", expectedResults.AllElements(), splits.AllElements());

        Console.WriteLine("*** Any Key to finish ***");
        Console.ReadKey();
    }
}

public static class Extensions
{
    public static string AllElements(this string[] str)
    {
        string output = "";
        if (str != null)
        {
            foreach (string item in str)
            {
                output += "'" + item + "',";
            }
        }
        return output;
    }
}

The Regex does the required job of splitting out words and operators into an array in the right sequence, but the result array contains many empty elements, and I can't work out why. Its not a serious problem as I just ignore empty elements when consuming the array but I'd like Regex to do all the work if possible, including ignoring spaces.

like image 324
Tom Brown Avatar asked Feb 28 '26 01:02

Tom Brown


1 Answers

Try this:

string[] splits = Regex.Split(removedSpaces, @"(?[A-Za-z0-9_]+)|(?[&!\|()]{1})").Where(x => x != String.Empty);
like image 168
Bridge Avatar answered Mar 01 '26 14:03

Bridge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!