【问题标题】:java regex split string with white space(except when both left and right was number or - )java 正则表达式用空格分割字符串(除了左右都是数字或 - )
【发布时间】:2014-06-13 07:45:01
【问题描述】:

我有这个字符串如何拆分 5-28 14:00 - 5-28 18:00 the60s(.corp)。我想用空格分割它,除非空格周围有数字或 -

我想要的结果是:

1. how 
2. to
3. split
4. 5-28 14:00 - 5-28 18:00
5. the60s(.corp)

谢谢。

以下是我的代码:

String str = "how do I split 5-28 14:00 - 5-28 18:00 the60s(.corp)";
    str = str.replaceAll("\\s+(?!(?=-|\\d+))", "@");

首先我用 @ 替换右边的空格,然后用 @ 分割字符串。但它不起作用。

【问题讨论】:

  • 一个好的起点是发布您尝试过的代码,解释什么不起作用,为什么,您期望什么以及发生了什么。

标签: java regex capture-group


【解决方案1】:

您可以为此使用环视:

(?<![-\d])\s+|\s+(?![\d-])

Code Demo

【讨论】:

  • 很抱歉忘记了 - ,正如标题所说的那样。
  • @anubhava - 很好的答案.. +1
  • 感谢@TheLostMind,很高兴它帮助了 OP
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-06
  • 1970-01-01
  • 2018-02-02
相关资源
最近更新 更多