![](/img/trans.png)
[英]Java: splitting a comma-separated string but ignoring commas in parentheses
[英]Java: splitting by comma and ignoring commas in tag <p>
我想用逗号分割字符串,但<p></p>
内的逗号应忽略。
例如,如果我有以下字符串
" Test1, test2, <p> test3, test4, test5, </p> , test6, test7"
我需要的结果是:
Test1
Test2
<p> test3, test4, test5, </p>
test6
test7
使用特殊字符如何实现呢?
您可以使用此正则表达式,(?![^<p>]*</p>)
拆分String:
String str = "Test1, test2, <p> test3, test4, test5, </p> , test6, test7";
String spl[] = str.split(",(?![^<p>]*</p>)");
输出量
Test1
test2
<p> test3, test4, test5, </p>
test6
test7
演示在这里:
您可以先使用“ p>”进行拆分: String[] temp = input.split("p>");
在示例中,您将在临时中拥有三个元素:
现在在所有临时字符串中,替换'<','p>'和'
最后,再次使用','分隔每一行。
除了一些(可轻松移动的)空字符串之外,它还应该工作
这应该可以,不是最理想的,抱歉,但是让我无所适从。
public static void main(String args[]) {
String x = " Test1, test2, <p> test3, test4, test5, </p> , test6, test7";
String newX[];
newX = x.split(",");
String newString = "";
int j = 0;
int count = 0;
for(int i = 0; i < newX.length; i ++) {
if(newX[i].contains("<p>")) {
count ++;
j=i;
while(!newX[i].contains("</p>")) {
newString = newString + "," + newX[i];
newX[i] = "";
i++;
}
newString = newString + "," + newX[i];
newX[i] = "";
newX[j] = newString;
newX[j] = newX[j].replaceFirst(",", "");
}
else
count++;
}
String output[] = new String[count];
j = 0;
for(int i = 0; i < newX.length; i++) {
if(newX[i] != "" && j < count) {
output[j] = newX[i];
System.out.println(output[j]);
j++;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.