在 Java 中用定界符拆分复杂字符串
Split complex string with delimiters in Java
我有一个简单的 XML 行,我想使用 String.split()
拆分,但它不能正常工作。
(<)position x="1" y="2" z="3" /(>) with no parentesis
这是我尝试应用的正则表达式:
String regex ="(<)position x=\"|\" y=\"|\" z=\"|\" /(>)";
预期结果是
1 2 3
你不能用 split()
方法做到这一点。它只会将字符串分成几部分,不会过滤掉单个组。相反,您可以使用 Pattern
和 Matcher
类
final String input = "<position x=\"1\" y=\"2\" z=\"3\" />";
final String regex = "<position\sx=\"([0-9]+)\"\sy=\"([0-9]+)\"\sz=\"([0-9]+)\"\s\/>";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
final String x = matcher.group(1);
final String y = matcher.group(2);
final String z = matcher.group(3);
System.out.println(x + " " + y + " " + z);
}
但是,如果您计划解析 XML,我 强烈建议 建议改用 XML 解析器。
我有一个简单的 XML 行,我想使用 String.split()
拆分,但它不能正常工作。
(<)position x="1" y="2" z="3" /(>) with no parentesis
这是我尝试应用的正则表达式:
String regex ="(<)position x=\"|\" y=\"|\" z=\"|\" /(>)";
预期结果是
1 2 3
你不能用 split()
方法做到这一点。它只会将字符串分成几部分,不会过滤掉单个组。相反,您可以使用 Pattern
和 Matcher
类
final String input = "<position x=\"1\" y=\"2\" z=\"3\" />";
final String regex = "<position\sx=\"([0-9]+)\"\sy=\"([0-9]+)\"\sz=\"([0-9]+)\"\s\/>";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
final String x = matcher.group(1);
final String y = matcher.group(2);
final String z = matcher.group(3);
System.out.println(x + " " + y + " " + z);
}
但是,如果您计划解析 XML,我 强烈建议 建议改用 XML 解析器。