我目前正在尝试使用 1_3_5_1,1_3_7_1,1_4_9_1
的输出解析字符串
我已经运行了一个 for 循环:
String[] row;
for(String value : selValues.split("\\,")){
System.err.println("value to be deleted :: "+value);
for(int i = 0; i <= 4; i++) {
row = value.split("\\_");
System.out.println("print row :: " + row[0]);
System.out.println("print row :: " + row[1]);
System.out.println("print row :: " + row[2]);
}
我正在 try catch 以“_”分隔的前 4 个。我正在寻找的是 row[] 是:
行[1,3,5,1]
行[1,3,7,1]
行[1,4,9,1]
因为这些是我将在查询中发送到数据库的值。
现在,我的输出只是重复 1,3,5,1。
如有任何帮助,我们将不胜感激。可能有更好的方法来做到这一点。谢谢!
解决方案
感谢大家的意见。我已经用它们清理了它并得到了这个:
if(selValues != null && !selValues.trim().equals("")){
for(String value : selValues.split(",")){
row = value.split("_");
try{
//database call here
}
catch (Exception e) {
e.printStackTrace();
}
}
}
最佳答案
您必须从正则表达式中删除 \\
。
这会做你需要的:
@Test
public void split2() {
String input = "1_3_5_1,1_3_7_1,1_4_9_1";
String[] csv = input.split(",");
for(String v : csv) {
String[] usv = v.split("_");
System.out.print("[");
for(int i = 0; i < usv.length; i++) {
System.out.print(usv[i]);
if(i < usv.length-1) {
System.out.print(", ");
}
}
System.out.println("]");
}
}
输出是
[1, 3, 5, 1]
[1, 3, 7, 1]
[1, 4, 9, 1]
关于java - 如何在 Java 中解析前 4 个值的定界符逗号分隔字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15396266/