1

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:

(\\"|[^" ])+|"(\\"|[^"])*"
3
  • 2
    Not enough back slashes. Commented Aug 26, 2012 at 13:17
  • hmm compared to the original perl pattern (\\"|[^" ])+|"(\\"|[^"])*" I always added one back slash for string escaping. where do I need more? Thanks! Ah I think I got it. I have to double each, of course. Commented Aug 26, 2012 at 13:18
  • hmm no, I don't manage to do it \: Commented Aug 26, 2012 at 13:19

3 Answers 3

2

Since the regexp string is first processed by the compiler before making it to the regexp processor, you need to double every backslahs in the expression, and add additional slashes for every doublequote.

 Pattern p = Pattern.compile("(\\\\\"|[^\" ])+|\"(\\\\\"|[^\"])*\""); 
Sign up to request clarification or add additional context in comments.

2 Comments

I think the original is already a regex, so for example \\" stands for a single backslash and a quote, which needs to be translated to \\\", as he did
@amit I think your interpretation is right, he meant for the regex engine to see \\" - a slash and a single quote. However, \\\" translates as \" after Java has its way with it, so you need two extra slashes.
2

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
}

2 Comments

Thank amit, also helpful, unfortunately I can only select one correct reply \:
@stefan.at.wpf No problems, glad I could help. You should accept the solution the solved your problem, as you did. You can upvote an answer if you find it helpful - no limits on these:)
0

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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.