如何在Java中使用正则表达式将“:abc,cde t”替换为“,abc | cde”?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在Java中使用正则表达式将“:abc,cde t”替换为“,abc | cde”?相关的知识,希望对你有一定的参考价值。
我有一个像下面的字符串列表:(没有引号)
"<someother string without :>:abc <some other string without >"
"<someother string without :>:abc,cde <some other string without >"
"<someother string without :>:abc,efg,cde <some other string without >"
"<someother string without :>:abc,cde <some other string without >"
想将它们转换为:
"<someother string without :>|abc <some other string without >"
"<someother string without :>|abc|cde <some other string without >"
"<someother string without :>|abc|efg|cde <some other string without >"
"<someother string without :>|abc|cde <some other string without >"
我想知道它是否可行?
谢谢
答案
不要认为你可以用正则表达式来做这件事,除非你多次应用它。你可以这样做:
public static String convert(String s) {
int start = s.indexOf(':') + 1;
int end = s.indexOf(' ', start);
return s.substring(0, start)
+ s.substring(start, end).replaceAll(",", "|")
+ s.substring(end, s.length());
}
另一答案
试试这个:
public class T28Regex {
public static void main(String[] args) {
String[] strings = { "<someother string without *>:abc <some other string without >",
"<someother string without *>:abc,cde <some other string without >",
"<someother string without *>:abc,efg,cde <some other string without >",
"<someother string without *>:abc,cde <some other string without >" };
for (String s : strings) {
System.out.println(s.substring(0, s.indexOf(":")) + "|"
+ s.substring(s.indexOf(":") + 1, s.indexOf(" ", s.indexOf(":"))).replaceAll(",", "|")
+ s.substring(s.indexOf(" ", s.indexOf(":"))));
}
}
}
另一答案
试试这个
function Replace_(str ) {
var patt = /(:)((([w]*(,)?)){2,})(\t<)/gi;
var res = str.replace(patt, function($1,$2,$3){
return $1.replace(/,/g, "|").replace(":", "|");
});
return res;
}
以上是关于如何在Java中使用正则表达式将“:abc,cde t”替换为“,abc | cde”?的主要内容,如果未能解决你的问题,请参考以下文章