[英]Using regex pattern in Java
I created a regex pattern that works perfect, but I can't get it working in Java: 我创建了一个完美的正则表达式模式,但我无法在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 根据http://myregextester.com/index.php在0组中
Now, how do I get those 6 values in Java? 现在,我如何在Java中获得这6个值? 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: 更新原始的perl正则表达式是:
(\\"|[^" ])+|"(\\"|[^"])*"
The matches()
method is matching the whole string to the regex - it returns true only if the entire string is matching matches()
方法将整个字符串与正则表达式匹配 - 只有在整个字符串匹配时才返回true
What you are looking for is the find()
method, and get the substring using the group()
method. 您正在寻找的是
find()
方法,并使用group()
方法获取子字符串。
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. matches()
尝试匹配整个字符串上的模式。 You should use find()
method of the Matcher object for your case. 您应该为您的案例使用Matcher对象的
find()
方法。
So the solution is: 所以解决方案是:
System.out.println(m.find());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.