The string to be parsed is given.

String line = "param1 param2 'param3 param3 param3' param4"; String[] params = line.split("Регулярное выражение"); 

At the output, params should be broken down by a пробелу and by 'тексту в кавычках' : That is:

 param1 param2 param3 param3 param3 param4 

I can't compose a similar regular expression, please help. Here is my option, but it does not work as it should:

 String[] params = line.split("[\\s(^'.'$)]"); 

    2 answers 2

    Another option:

     String line = "param1 param2 'param3 param3 param3' param4"; System.out.println(Arrays.asList(line.replaceAll("\'", "").split("'?(\\s|$)(?=(([^']*'){2})*[^']*$)'?"))); // [param1, param2, param3 param3 param3, param4] 

    Using apache-commons-lang

     StrTokenizer tokenizer = new StrTokenizer(line, ' ', '\''); while(tokenizer.hasNext()) { System.out.println(tokenizer.nextToken()); } // param1 // param2 // param3 param3 param3 // param4 

    The last option (honestly steal from here ):

     ArrayList<String> list = new ArrayList<String>(); Matcher m = Pattern.compile("((?<=')[^']*(?='(\\s|$)+)|(?<=\\s|^)[^\\s']*(?=\\s|$))").matcher(line); while ( m.find() ) { list.add(m.group(1)); } System.out.println(list); // [param1, param2, param3 param3 param3, param4] 
    • Not universal. If you add another param3, it does not work: param1 param2 'param3 param3 param3 param3' param4 - CJ1
    • one
      This expression does not parse a single quote, two quotes in a row, i.e. what can be considered a syntax error of the original expression. You can add as many parameters as you like. - enzo
    • Indeed .... Apparently the first time I somehow did not correctly entered. Thank. I will understand your regular expression! - CJ1
    • No, the regular season is not very good. It does not remove the quotation mark at the beginning of the line. The method proposed by @Arsenicum — match parameter matches, rather than separators — initially more correct. Corrected the answer. disassemble regulars conveniently here. - enzo
    • Arsenicum method leaves quotes. This method leaves one quote at the beginning of a line. Then I will try myself to make a suitable reg. - CJ1

    Try this code:

     String line = "param1 param2 'param3 param3 param3' param4"; ArrayList<String> list = new ArrayList<String>(); Matcher m = Pattern.compile("([^\']\\S*|\'.+?\')\\s*").matcher(line); while (m.find()) list.add(m.group(1).replaceAll("'", "")); System.out.println(list); 

    The result will be: [param1, param2, param3 param3 param3, param4]

    We look at the group without quotes [^\']\\S* or the group with quotes \'.+?\' .

    • Improved your version ((? <= '). +? (? =')) | ([^ \ '] \\ S *) \\ s * now as needed) - CJ1
    • @ CJ1, if you change the line to list.add(m.group(1).replaceAll("'", "")); , then you will have a result without single quotes. - Arsenicum