Home java java. String.Split (Regex) Parsing string

java. String.Split (Regex) Parsing string

Author

Date

Category

is given a string that you need to paint on the components

string line = "Param1 param2 'param3 param3 param3' param4";
String [] Params = Line.split ("Regular expression");

Output Params must be broken by space and 'text in quotes' :
That is:

param1
Param2.
Param3 Param3 Param3.
Param4.

I can not make a similar regular expression, please help.
Here is my option, but it does not work as needed:

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

Answer 1, Authority 100%

Another option:

string line = "Param1 param2 'param3 param3 param3' param4";
System.out.PrintLN (array.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.

Last option (honestly shy Hence ):

ArrayList & lt; String & GT; List = New ArrayList & LT; String & GT; ();
Matcher M = Pattern.compile ("((? & Lt; = ') [^'] * (? = '(\\ s | $) +) | (? & Lt; = \\ s | ^) [^ \\ s'] * (? = \\ s | $)) "). Matcher (Line);
While (M.Find ()) {
  List.Add (M.Group (1));
}
System.out.PrintLN (List);
// [Param1, Param2, Param3 Param3 Param3, Param4]

Answer 2, Authority 167%

Try such a code:

string line = "Param1 param2 'param3 param3 param3' param4";
ArrayList & LT; String & GT; List = New ArrayList & LT; String & GT; ();
Matcher M = Pattern.compile ("([^ \ '] \\ s * | \' +? \ ') \\ s *"). Matcher (Line);
While (M.Find ())
  List.Add (M.Group (1) .Replaceall ("'", ""));
System.out.PrintLN (List);

In the end, it will turn out: [Param1, Param2, Param3 Param3 Param3, Param4]

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

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions