Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing escape sequences in the args[] array on Windows

I was reading SCJP guide, and found the following question, it's looks very easy and might be easy for someone. But, i was really stuck to find out the solution.

import java.util.regex.*;

class study{

    public static void main(String[] args) {
      Pattern p = Pattern.compile(args[0]);
      Matcher m = p.matcher(args[1]);
      boolean b=false;
      while(b=m.find()){
      System.out.print(m.start()+" "+m.group());
     }
    }

}

In that question the command line argument was given like

java study "\d*" ab34ef

And, said what would be the ouput, my guess was 334 or 234 and it was in that option. But, answer (on Windows) was 01234456. So, my first question is How ??

Now, people say, why didn't you tried. Then, i will say, Yes i did. But, in my case I didn't get any output on my screen. Then, i tried to figure out considering all type of input and their values.

enter image description here

In the above screenshot, second output shown, when i included System.out.print(args[0]+" "+args[1]); inside main method.

Even, i changed the command line to this

java study "\\d*" ab34ef

Then also, i didn't get any output. So, anyone explain all this thing .

OUTPUT==

java study "\d*" ab34ef
No output
java study "\\d*" ab34ef
No output

Then i add System.out.print(args[0]+" "+args[1]); inside main method.

java study "\d*" ab34ef
\Document and Setting ab34ef
java study "\\d*" ab34ef
\\d* ab34ef

Note : No output means it is not showing anything.

like image 611
Ravi Avatar asked Oct 05 '22 14:10

Ravi


1 Answers

Actually what happens is, when you pass \d* as command line argument, it is treated as \d followed by * wildcard. So, the argument is replaced by all the files starting with \d in that directory. (This behaviour happens on Windows. Though I don't know about Linux, as I haven't used it).

So, you are not passing the regular expression, rather the file/directory names starting with \d in to your program.

Try to print the arguments in your code: -

System.out.println(args[0] + " : " + args[1]);

This will give you some file/directory names starting with \d...


Workaround: -

If you want to pass regex, you can use a work around. Pass " \d*" as regex with a space in the front, and in your code, use args[0].trim() or args[0].replace(" ", ""); instead of args[0].

So, call it as: -

java Foo " \d*" ab34ef

And change your code to: -

Pattern p = Pattern.compile(args[0].replace(" ", ""));
Matcher m = p.matcher(args[1]);

This will do the job for you.


Now that was the problem of passing Regex through command line.

As for why you are getting that output, Check out this answer - string-replaceall-strange-behaviour, which is about similar problem. You will get an idea of why this is happening.

like image 154
Rohit Jain Avatar answered Oct 10 '22 03:10

Rohit Jain