I created a regex pattern that works perfect, but I can't get it working in Java:
(\\"|[^" ])+|"(\\"|[^"])*"
applied to
robocopy "C:\test" "C:\test2" /R:0 /MIR /NP
gives (as it should)
[0] => robocopy
[1] => "C:\test"
[2] => "C:\test2"
[3] => /R:0
[4] => /MIR
[5] => /NP
in group 0 according to http://myregextester.com/index.php
Now, how do I get those 6 values in Java? I tried
Pattern p = Pattern.compile(" (\\\"|[^\" ])+ | \"(\\\"|[^\"])*\" ");
Matcher m = p.matcher(command);
System.out.println(m.matches()); // returns false
but the pattern doesn't even match anything at all?
Update The original perl regex was:
(\\"|[^" ])+|"(\\"|[^"])*"
The matches()
method is matching the whole string to the regex - it returns true only if the entire string is matching
What you are looking for is the find()
method, and get the substring using the group()
method.
It is usually done by iterating:
while (m.find()) {
.... = m.group();
//post processing
}
由于regexp字符串在进入regexp处理器之前首先由编译器处理,因此需要将表达式中的每个backslah加倍,并为每个doublequote添加额外的斜杠。
Pattern p = Pattern.compile("(\\\\\"|[^\" ])+|\"(\\\\\"|[^\"])*\"");
matches()
tries to match the pattern on entire string. You should use find()
method of the Matcher object for your case.
So the solution is:
System.out.println(m.find());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.