C # string handling how to get path and arguments from string

I have a quoted string around the path as follows:

"C: \ Program Files (x86) \ Windows Media Player \ wmplayer.exe" arg1 arg2

If I use Text.Split(new Char[] { ' ' }, 2); then I get the first space.

How to get the path and arguments?

+4
source share
3 answers

Try splitting it with double quotes (Text.Split (new Char [] {'/ "'}, 3);), then taking the last line in this array and again breaking it into a space.

 string[] pathAndArgs = Text.Split(new Char[] { '/"' }, 3); string[] args = pathAndArgs[2].Split(new Char[] { ' ' }, 2); 

I may have a syntax error, but you understand what I mean.

+2
source

Use a regular expression, for example: ("".*?"")|(\S+)

So your code would be something like this:

 Regex r = new Regex(@"("".*?"")|(\S+)"); MatchCollection mc = r.Matches(input); for (int i = 0; i < mc.Count; i++) { Console.WriteLine(mc[i].Value); } 
+4
source

Make text.split and go back from the end of the array.

 var input = "C:\\blah\\win.exe args1 args2"; var array = input.split(' '); var arg1 = array[array.length -2]; var arg2 = array[array.length -1]; 
+1
source

All Articles