[英]split text into array using regex in Java
我需要一些关于字符串split()
方法的正则表达式的帮助。 我想拆分的字符串如下所示:
<code a="1234" n1="John doe" n2="1/3 forest" o1="game dev" id_fk="2"/>
它总是以<code
开头并以 `/> 结尾
我希望结果看起来像这样:
a="1234"
n1="John doe"
n2="1/3 forest"
o1="game dev"
id_fk="2"
我尝试使用regex101创建正则表达式,目前我的表达式是(\S+=".*?")
,所以我想要的字符串在这种情况下是分隔符,我不知道如何否定这个表达式或写出不同的表达式来给我正确的结果。
提前谢谢你的帮助
您的方法有效,此代码
String input = "<code a=\"1234\" n1=\"John doe\" n2=\"1/3 forest\" o1=\"game dev\" id_fk=\"2\"/>";
Matcher matcher = Pattern.compile("(\\S+=\"[^\"]+\")").matcher(input);
while(matcher.find()) {
System.out.println(matcher.group(1));
}
印刷
a="1234"
n1="John doe"
n2="1/3 forest"
o1="game dev"
id_fk="2"
你传递给split
的东西是separator 。 例如,您想要的数据之间的东西。
您的正则表达式匹配...您想要的数据,这意味着您返回的是空格,仅此而已。
您两次使用了错误的工具来完成这项工作。
[A] 这是 HTML。 'RegularExpression' 中的 'regular' 不是随机名称。 正则表达式不是由“常规先生”发明的。 它们指的是一种语法:有些语法是“常规的”,有些则不是。 您不能使用正则表达式解析非常规语法。 HTML 不正常。 我可以制作有效的 HTML ,这将使您想要制作的任何正则表达式都失败。 也许它不太可能发生,但它们是休息时间。
[B] 即使你决定把它扔给狼并继续走这条错误的道路, split
也不是正确的工具。 做一个模式 object,做一个匹配器,反复调用find
:
Pattern p = Pattern.compile("([a-z]+)\\s*=\\s*\"([^\"]*)\"");
Matcher m = p.matcher("<code a=\"1234\"...>");
while (m.find()) {
String key = m.group(1);
String value = m.group(2);
System.out.println(key); // prints 'a'
System.out.println(value); // prints value
}
保持简单,并假设您只需要使用顶级非嵌套单个 XML 标签执行此操作,我们可以尝试:
String input = "<code a=\"1234\" n1=\"John doe\" n2=\"1/3 forest\" o1=\"game dev\" id_fk=\"2\"/>";
String[] parts = input.replaceAll("^<\\S+\\s+|\\s*/>$", "").split("\\s+");
System.out.println(Arrays.toString(parts));
// [a="1234", n1="John, doe", n2="1/3, forest", o1="game, dev", id_fk="2"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.