[英]Split string with string and retrieve value c#
I have below string 我有下面的字符串
string arguments = "-p=C:\Users\mplususer\Documents\SharpDevelop Projects\o9\o9\bin\Debug\o9.exe""-t=False""-r=TestRun";
I want to split string with "-t="
and get false
value 我想用
"-t="
拆分字符串并获取false
值
if (arguments.Contains("-t="))
{
string[] value = arguments.Split(new string[] { "\"-t=" }, StringSplitOptions.None);
if (value.Length != 0)
{
mode = value[1].Replace("\"", "");
}
}
Simply make an IndexOf
: 只需制作一个
IndexOf
:
var i = myString.IndexOf("-t=") + 3;
if(i != -1)
value = myString.SubString(i, myString.IndexOf("\"", i) - i);
You can also use a regex for this: 您也可以使用正则表达式:
var r = new Regex("-t (true|false)");
var g = r.Match(myString).Groups;
if(g.Count > 1)
value = Convert.ToBoolean(g[1].ToString());
You can do it also like this like your approach without regex: 您也可以这样做,就像没有正则表达式的方法一样:
string arguments = "-p=C:\\Users\\mplususer\\Documents\\SharpDevelop Projects\\o9\\o9\\bin\\Debug\\o9.exe\" \"-t=False\" \"-r=TestRun";
if (arguments.Contains("-t="))
{
string splitted = arguments.Split(new string[] { "\"-t=" }, StringSplitOptions.None)[1];
string value = splitted.Split(new string[] { "\"" }, StringSplitOptions.None)[0];
}
When you split on "-t", you get two fragments. 拆分“-t”时,会得到两个碎片。 The fragment after that delimiter also contains a "-r" option - which is the issue you are probably seeing.
该分隔符后面的片段还包含一个“-r”选项 - 这是您可能会看到的问题。
If you know that the "-t" option is always followed by a "-r", you could simply split on new string[] { "\\"-t=", "\\"-r=" }
. 如果你知道 “-t”选项后面总是跟一个“-r”,你可以简单地拆分
new string[] { "\\"-t=", "\\"-r=" }
。 Then you get three fragments and you still want the second one (at index 1). 然后你得到三个片段,你仍然想要第二个(在索引1处)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.