java - 使用正则表达式将字符串拆分为两个字符串

标签 java regex string split

这个问题之前被问过几次,但我找不到我的问题的答案: 我需要将一个字符串分成两个字符串。第一部分是日期,第二部分是文本。这是我到目前为止得到的:

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/

相关文章:

Java Map ReplaceAll 与多个字符串匹配

java - 即使使用 INNER JOIN FETCH 查询也会出现意外的 JavaAssistLazyInitializer

java - 无法在 Android Studio 中添加操作栏项目

mysql - sql匹配模式正则表达式查询

python - Re.sub 不适合我

node.js - 如何在 Node.js 中检查字符串是明文还是 base64 格式

java - 当 EditText 更改时如何从 ArrayAdapter 中删除项目?

java - 加载包含在 .Jar 文件或类路径中的资源(图像)

不包含字符串的所有字符串的正则表达式?

c++ - 为什么在没有初始化的情况下获取string[0]也是有效的?