簡體   English   中英

在C#中使用多個分隔符拆分字符串

[英]Split string with multiple separators in C#

我在使用分隔符&&||分割C#中的字符串時遇到問題

例如,字符串可能如下所示:

"(abc)&&(rfd)&&(5)||(hh)&&(nn)||(iu)"

碼:

string[] value = arguments.Split(new string[] { "&&" }, StringSplitOptions.None);

我需要在沒有()括號的數組中拆分或檢索值 - 我需要輸出

"abc" "rfd" "5" "nn" "iu"

我需要一個數組

Dictionary<string, string> dict = new Dictionary<string, string>();
            dict.Add("a", "value1");
            dict.Add("abc", "value2");
            dict.Add("5", "value3");
            dict.Add("rfd", "value4");
            dict.Add("nn", "value5");
            dict.Add("iu", "value6");

foreach (string s in strWithoutBrackets)
{
     foreach (string n in dict.Keys)
     {
          if (s == n)
          { 
               //if match then replace dictionary value with s
          }
      }
}

 ///Need output like this
 string outputStr = "(value1)&&(value2)&&(value3)||(value4)&&(value5)||(value6)";

你應該試試這些:

string inputStr = "(abc)&&(rfd)&&(5)||(hh)&&(nn)||(iu)";
string[] strWithoutAndOR = inputStr.Split(new string[] { "&&","||" }, StringSplitOptions.RemoveEmptyEntries);
string[] strWithoutBrackets = inputStr.Split(new string[] { "&&","||","(",")" }, StringSplitOptions.RemoveEmptyEntries);

看看這個工作實例

根據MSDN docs: String.Split返回一個字符串數組,該數組包含此實例中由指定字符串或Unicode字符數組的元素分隔的子字符串。 split方法具有很少的重載方法,您可以在此方案中使用String.Split方法(String [],StringSplitOptions) ,您可以在其中指定要為拆分操作引用的子字符串。 StringSplitOptions.RemoveEmptyEntries將幫助您從拆分結果中刪除空條目

如果我理解你的問題,你有一個像這樣的字符串:

"(abc)&&(rfd)&&(5)||(hh)&&(nn)||(iu)"

並希望輸出如下:

"(value1)&&(value2)&&(value3)||(value4)&&(value5)||(value6)"

通過在您提供的字典中查找匹配的字符串(例如"abc" )找到每個value*值。

如果是這種情況,您可以使用帶有MatchEvaluator的正則表達式來執行字典查找。

class Program
{
    private static Dictionary<string, string> _dict = new Dictionary<string, string>
    {
        {"a", "value1"},
        {"abc", "value2"},
        {"5", "value3"},
        {"rfd", "value4"},
        {"nn", "value5"},
        {"iu", "value6"}
    };

    private static void Main(string[] args)
    {
        string input = "(abc)&&(rfd)&&(5)||(hh)&&(nn)||(iu)";

        string output = Regex.Replace(input, @"(?<=\()\w+(?=\))", Lookup);

        Console.WriteLine(output);
    }

    private static string Lookup(Match m)
    {
        string result;
        _dict.TryGetValue(m.Value, out result);
        return result;
    }
}

正則表達式(?<=\\()\\w+(?=\\))匹配由大寫或小寫字母組成的非零長度字符串,下划線或數字: \\w+ ,后面的斷言后面的括號(?<=\\()和關閉括號的前瞻斷言(?=\\))

請注意,輸入字符串"hh"匹配的其中一個字符串不在您提供的字典中。 在這種情況下,我選擇返回null ,您可能希望拋出異常或以其他方式處理此類錯誤。

在簡單的情況下, MatchEvaluator可以替換為lambda表達式。

你應該試試這個代碼:

string value = "(abc)&&(rfd)&&(5)||(hh)&&(nn)||(iu)";
string[] splitVal = value.Split(new string[] { "&&", "||" },StringSplitOptions.None);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM