我第一次使用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);
}
以上代码的输出类似于(018020000304050.12500)
实际上我想要这样的输出,(“ F”,“ 01”,“ T”,“ 8”,“ B”,“ 02”,“ S”,“ 00003”,“ H”,“ 04” ,“ Z”,“ 05”,“ C”,“ 0.12500”)。
意味着所需的输出包含模式字符和拆分值。
你能建议我吗?
答案 0 :(得分:3)
我已经创建了一个样本,尝试一下,让我知道它是否是您想要的。
public class Main {
public static void main(String[] args) {
String line = "F01T8B02S00003H04Z05C0.12500";
String pattern = "([A-Z][a-z]*)(((?=[A-Z][a-z]*|$))|\\d+(\\.\\d+)?)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
HashMap<String, String> mHash = new LinkedHashMap<>();
while (m.find()) {
mHash.put(m.group(1), m.group(2));
}
System.out.println(mHash.toString());
}
}
输出为:
F 01
T 8
B 02
S 00003
H 04
Z 05
C 0.12500
使用LinkedHashMap
public class Main {
public static void main(String[] args) {
String line = "F01T8B02S00003H04Z05C0.12500";
String pattern = "([A-Z][a-z]*)(((?=[A-Z][a-z]*|$))|\\d+(\\.\\d+)?)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
HashMap<String, String> mHash = new LinkedHashMap<>();
while (m.find()) {
mHash.put(m.group(1), m.group(2));
}
System.out.println(mHash.toString());
}
}
输出为:
{F = 01,T = 8,B = 02,S = 00003,H = 04,Z = 05,C = 0.12500}
答案 1 :(得分:2)
您可以在String#split的[A-Z]
上使用keeps the delimiter as separated item:
String line = "F01T8B02S00003H04Z05C0.12500";
String[] result = line.split("((?<=[A-Z])|(?=[A-Z]))");
System.out.println(java.util.Arrays.toString(result));
这将导致字符串数组:
[F, 01, T, 8, B, 02, S, 00003, H, 04, Z, 05, C, 0.12500]
答案 2 :(得分:0)
以上所有答案均正确。 我也通过下面的代码得到了解决方案。
String line = "F01T8B02S00003H04Z05C0.12500A03";
String[] commands = line.split("(?<=[BCFHSTZ])|(?=[BCFHSTZ])");
for (String str: commands) {
System.out.print(str);
}
谢谢大家的帮助。