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

sga*_*mer 1 java regex

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

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

任何帮助将不胜感激.

Bra*_*raj 11

您可以使用Positive Lookbehind和Lookahead在非数字和数字之间添加空格

System.out.println("FR3456".replaceAll("(?<=\\D)(?=\\d)"," "));
Run Code Online (Sandbox Code Playgroud)

这里

\D  A non-digit: [^0-9]
\d  A digit: [0-9]
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请查看Java Regex Pattern


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

这是在线演示

模式说明:

  (?<=                     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
Run Code Online (Sandbox Code Playgroud)