parse a string with quote and operators in Java

Hello ,
  How do I parse this string in java The value in the string is separated by 1 or more space

queryStr= XX -YY "this is test"   
should return
"this is a test"

Open in new window

queryStr = -XX YY -"this is a test"
Should return
-"this is a test"

Open in new window

I have this pattern in my java code
 Matcher m = Pattern.compile("([^\"]\\S*|\".+?\")\\s*").matcher(queryStr);

It parses the first string correctly. However, it does not work for the second case (the string in quote with the operator in front"

How can I fix the pattern to make it work in both cases.

Thanks for your help
Who is Participating?
Carl BohmanConnect With a Mentor Commented:
I did not know that - and + were both possible based on the original question.  Here is an updated version:

Matcher m = Pattern.compile("((?:[-+][^\"\\s]|[^-+\"\\s])\\S*|[-+]?\".+?\")\\s*").matcher(queryStr);

Open in new window

Note that I added the plus everywhere the dash was included in the regex to ensure consistency.
Carl BohmanCommented:
This may work:

Matcher m = Pattern.compile("((?:-[^\"\\s]|[^-\"\\s])\\S*|-?\".+?\")\\s*").matcher(queryStr);

Open in new window

SiemensSENAuthor Commented:
Thank you Carl . It works 90% . However it does not work for this string

queryStr= -"No files to process" +"Posting file "

Thanks for your help
SiemensSENAuthor Commented:
Thanks you very much for the help
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.