这个问题之前被问过几次,但我找不到我的问题的答案: 我需要将一个字符串分成两个字符串。第一部分是日期,第二部分是文本。这是我到目前为止得到的:
String test = "24.12.17 18:17 TestString";
String[] testSplit = test.split("\\d{2}.\\d{2}.\\d{2} \\d{2}:\\d{2}");
System.out.println(testSplit[0]); // "24.12.17 18:17" <-- Does not work
System.out.println(testSplit[1].trim()); // "TestString" <-- works
我可以提取“TestString”,但我错过了日期。有没有更好(甚至更简单)的方法?非常感谢您的帮助!
最佳答案
跳过正则表达式;使用三个字符串
你工作太辛苦了。无需将日期和时间连为一体。正则表达式很棘手,而且生命短暂。
只需使用简单的 String::split
三个 部分,并重新组合日期时间。
String[] pieces = "24.12.17 18:17 TestString".split( " " ) ; // Split into 3 strings.
LocalDate ld = LocalDate.parse( pieces[0] , DateTimeFormatter.ofPattern( "dd.MM.uu" ) ) ; // Parse the first string as a date value (`LocalDate`).
LocalTime lt = LocalTime.parse( pieces[1] , DateTimeFormatter.ofPattern( "HH:mm" ) ) ; // Parse the second string as a time-of-day value (`LocalTime`).
LocalDateTime ldt = LocalDateTime.of( ld , lt ) ; // Reassemble the date with the time (`LocalDateTime`).
String description = pieces[2] ; // Use the last remaining string.
查看此code run live at IdeOne.com .
ldt.toString(): 2017-12-24T18:17
description: TestString
提示:如果您对该输入有任何控制权,请切换到使用标准 ISO 8601文本中日期时间值的格式。 java.time类在生成/解析字符串时默认使用标准格式。
关于java - 使用正则表达式将字符串拆分为两个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45653115/