简体   繁体   中英

Splitting an input String

I've the following Query String,

QUERY 192.168.1.0 0 2016-08-25 18:32 2016-08-26 18:31

I want to split it into 5 string objects such that 2016-08-25 18:32 and 2016-08-26 18:31 are parsed as one object.

String[] arr = str.split(" ");

Splits the String into 7 strings splitting the dates. I'm not sure how to do it using regular expressions using Java. Any help appreciated.

as long as the positions of the items are static, simply manipulate your output array after the split:

String sdate = arr[3] + ' ' + arr[4];
String edate = arr[5] + ' ' + arr[6];

if needed, make a new array:

String[] arr2 = {arr[0], arr[1], arr[2], sdate, edate};

good luck!

实现上述目标的另一种简便方法是使用regex将字符串按空格分隔到新行上。

str.replaceAll("\\\\s", "\\n")

You totally don't need a RegEx here. Parsing a string with regex is a rather complex process, and in your situation where you have static positions in string and can just concatenate parts - regex is an obvious overkill.

And by the way, regexes almost always make your code much less readable. So with regex here you will end up with a lot less readable and performant code.

Vote against RegEx.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM