Extract string between characters

I would like to extract 2 arguments from a given string using regex. For example:

C: \ Users "C: \ Program files"

C: \ mytext.txt mytext2.txt

The output will be C: \ Users and C: \ Program files

C: \ mytext.txt and mytext2.txt

If the line is between ", it may contain spaces, otherwise it should be without them. So far I have managed to extract arguments between" ", but I can’t figure out how to extract them when one argument has" "and the other does not (like in the example above).

Pattern p = Pattern.compile("\"(.*?)\"");
    Matcher m = p.matcher(string);
    while(m.find()){
        System.out.println(m.group(1));
    }
+4
source share
1 answer

You can use this regex to match:

Pattern p = Pattern.compile("\"[^\"]*\"|\\S+");

RegEx Demo

+2
source

Source: https://habr.com/ru/post/1623316/


All Articles