Reputation: 2215
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
if (arguments.Contains("-t="))
{
string[] value = arguments.Split(new string[] { "\"-t=" }, StringSplitOptions.None);
if (value.Length != 0)
{
mode = value[1].Replace("\"", "");
}
}
Upvotes: 1
Views: 198
Reputation: 2107
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];
}
Upvotes: 1
Reputation: 37000
Simply make an 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());
Upvotes: 2
Reputation: 39284
When you split on "-t", you get two fragments. The fragment after that delimiter also contains a "-r" option - which is the issue you are probably seeing.
If you know that the "-t" option is always followed by a "-r", you could simply split on new string[] { "\"-t=", "\"-r=" }
. Then you get three fragments and you still want the second one (at index 1).
Upvotes: 0