如何用另一组数字用垂直线替换数字
例如,我有一组数字如下
"118|142|4000000|99|8|1372055573|0"
"119|12|600|9|8|1866573|0"
"120|126|85600|9|8|1866573|0"
我希望将结尾的所有号码替换为"x|y|2900|99|20|99999999|0"
x
,y
仍然是相同的数字。
然后在运行代码之后,总结就是
"118|142|2900|99|20|99999999|0"
"119|12|2900|99|20|99999999|0"
"120|126|2900|99|20|99999999|0"
答案 0 :(得分:1)
这是一个简单的解决方案
String str[] = new String[]{"118|142|4000000|99|8|1372055573|0", "119|12|600|9|8|1866573|0"};
String[] oldTokens = str[0].split("[|]");
String[] newTokens = str[1].split("[|]");
StringBuffer strBuff = new StringBuffer();
for(int i = 0 ; i < newTokens.length ; i ++) {
if(i < 2)
strBuff.append(oldTokens[i]);
else strBuff.append(newTokens[i]);
if(i < newTokens.length) {
strBuff.append("|");
}
}
System.out.println(strBuff.toString());
答案 1 :(得分:1)
正则表达式可以满足您的需求:
"((?:[^|]+\|){2})[^"]+"
替换为:
"$12900|99|20|99999999|0"
演示RegExr
Java使用:
String in = "\"118|142|4000000|99|8|1372055573|0\",\"119|12|600|9|8|1866573|0\",\"120|126|85600|9|8|1866573|0\"";
String out = in.replaceAll("\"((?:[^|]+\\|){2})[^\"]+\"", "\"$12900|99|20|99999999|0\"");
答案 2 :(得分:0)
Apache Commons Lang有一个StringUtils类,它有一个join函数,它将数组连接起来构成一个String。
以下是一行
的示例public class Test {
public static void main() {
String s = "118|142|4000000|99|8|1372055573|0";
String[] parts = s.split("|");
parts[2] = "2900";
parts[3] = "99";
parts[4] = "20";
parts[5] = "99999999";
parts[6] = "0";
String newString = StringUtils.join(parts, "|");
}
}
答案 3 :(得分:0)
这是一个简单的解决方案。但是这段代码是可重用的。你可以随意使用它。
String original = "118|142|4000000|99|8|1372055573|0";
String toFind = "4000000|99|8|1372055573|0";
String toReplace = "2900|99|20|99999999|0";
int ocurrence = 1;
String replaced = replaceNthOcurrence(original, toFind, toReplace,ocurrence);
System.out.println(replaced);
replaceNthOcurrence
的功能代码:
public static String replaceNthOcurrence(String str, String toFind, String toReplace, int ocurrence) {
Pattern p = Pattern.compile(Pattern.quote(toFind));
Matcher m = p.matcher(str);
StringBuffer sb = new StringBuffer(str);
int i = 0;
while (m.find()) {
if (++i == ocurrence) { sb.replace(m.start(), m.end(), toReplace); break; }
}
return sb.toString();
}