我有一個正則表達式可以在簡單的邏輯語句中分割出單詞運算符和括號(例如「WORD1 & WORD2 |(WORd_3 &!word_4)」。我提出的正則表達式是 「([A-ZA-Z0-9 _] +?)|(?[& \ |!(){1})」 這裏是一個快速測試程序Regex.Split在結果數組中添加空字符串
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;
}
}
。
正則表達式完成將單詞和運算符按正確順序拆分爲數組所需的工作,但結果數組包含ma是空的元素,我無法弄清楚爲什麼。它不是一個嚴重的問題,因爲我在使用數組時忽略了空元素,但我希望Regex儘可能地完成所有工作,包括忽略空格。
你在哪裏期待輸入字符串中的空格去?你沒有他們在你預期的陣列,但我不知道你在哪裏擺脫他們在任何地方... – Chris 2012-03-07 12:04:25
@Chris沒有空格,他用testExpression.Replace(「」,「」); – 2012-03-07 12:11:22
@DorCohen:啊,我真想知道我是否在密集。看起來我是。;-) – Chris 2012-03-07 12:13:30