第一次使用Regex语句。
我有java regex语句,该语句按模式将String拆分为一些字符列表。
String line = "F01T8B02S00003H04Z05C0.12500";
Pattern pattern = Pattern.compile("([BCFHSTZ])");
String[] commands = pattern.split(line);
for (String command : commands) {
System.out.print(command);
}
Run Code Online (Sandbox Code Playgroud)
上面代码的输出就像(018020000304050.12500)
其实我想要这样的输出,(“ F”,“ 01”,“ T”,“ 8”,“ B”,“ 02”,“ S”,“ 00003”,“ H”,“ 04”,“ Z “,” 05“,” C“,” 0.12500“)。
表示所需的输出同时包含模式字符和拆分值。
你能建议我吗?
您可以使用String#split将分隔符[A-Z]保留为分隔项:
String line = "F01T8B02S00003H04Z05C0.12500";
String[] result = line.split("((?<=[A-Z])|(?=[A-Z]))");
System.out.println(java.util.Arrays.toString(result));
Run Code Online (Sandbox Code Playgroud)
这将产生字符串数组:
[F, 01, T, 8, B, 02, S, 00003, H, 04, Z, 05, C, 0.12500]
Run Code Online (Sandbox Code Playgroud)