JAVA正则表达式在字符和数字之间添加空格

时间:2014-08-10 16:56:03

标签: java regex

我正在尝试编写一个java正则表达式来在字符和数字之间添加空格。我尝试了一些,但它不起作用。

例如:此字符串" FR3456",我希望将其转换为" FR 3456"。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:11)

您可以使用Positive Lookbehind & Lookahead

在非数字和数字之间添加空格
System.out.println("FR3456".replaceAll("(?<=\\D)(?=\\d)"," "));

下面

\D  A non-digit: [^0-9]
\d  A digit: [0-9]

了解更多信息,请查看Java Regex Pattern


或使用(?<=[^0-9])(?=[0-9])

这是online demo

模式说明:

  (?<=                     look behind to see if there is:
    [^0-9]                   any character except: '0' to '9'
  )                        end of look-behind
  (?=                      look ahead to see if there is:
    [0-9]                    any character of: '0' to '9'
  )                        end of look-ahead
相关问题