我在用分隔符&&
和分隔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)";
如果我正确理解了您的问题,则您将得到一个类似以下的字符串:
"(abc)&&(rfd)&&(5)||(hh)&&(nn)||(iu)"
并想要这样的输出:
"(value1)&&(value2)&&(value3)||(value4)&&(value5)||(value6)"
value*
通过"abc"
在您提供的词典中查找匹配的字符串(例如)找到每个值的位置。
如果是这种情况,您可以将正则表达式与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表达式代替。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句