Java 替换所有字符串
Java replaceALL for string
我有一个字符串:
100-200-300-400
我想将破折号替换为“,”并添加单引号,使其变为:
'100','200','300','400'
我目前的代码只能将“-”替换为“,”,如何加上单引号?
String str1 = "100-200-300-400";
split = str1 .replaceAll("-", ",");
if (split.endsWith(","))
{
split = split.substring(0, split.length()-1);
}
您可以使用
split = str1 .replaceAll("-", "','");
split = "'" + split + "'";
如果您使用的是 java 1.8,那么您可以创建一个 StringJoiner 并将字符串拆分为 -
。这会节省一些时间,但是如果您考虑到例如跟踪 -
会更安全。
一个小样本可能看起来像这样。
String string = "100-200-300-400-";
String[] splittet = string.split("-");
StringJoiner joiner = new StringJoiner("','", "'", "'");
for(String s : splittet) {
joiner.add(s);
}
System.out.println(joiner);
这对你有用:
public static void main(String[] args) throws Exception {
String s = "100-200-300-400";
System.out.println(s.replaceAll("(\d+)(-|$)", "'',").replaceAll(",$", ""));
}
O/P :
'100','200','300','400'
或者(如果你不想使用 replaceAll()
两次。
public static void main(String[] args) throws Exception {
String s = "100-200-300-400";
s = s.replaceAll("(\d+)(-|$)", "'',");
System.out.println(s.substring(0, s.length()-1));
}
我有一个字符串:
100-200-300-400
我想将破折号替换为“,”并添加单引号,使其变为:
'100','200','300','400'
我目前的代码只能将“-”替换为“,”,如何加上单引号?
String str1 = "100-200-300-400";
split = str1 .replaceAll("-", ",");
if (split.endsWith(","))
{
split = split.substring(0, split.length()-1);
}
您可以使用
split = str1 .replaceAll("-", "','");
split = "'" + split + "'";
如果您使用的是 java 1.8,那么您可以创建一个 StringJoiner 并将字符串拆分为 -
。这会节省一些时间,但是如果您考虑到例如跟踪 -
会更安全。
一个小样本可能看起来像这样。
String string = "100-200-300-400-";
String[] splittet = string.split("-");
StringJoiner joiner = new StringJoiner("','", "'", "'");
for(String s : splittet) {
joiner.add(s);
}
System.out.println(joiner);
这对你有用:
public static void main(String[] args) throws Exception {
String s = "100-200-300-400";
System.out.println(s.replaceAll("(\d+)(-|$)", "'',").replaceAll(",$", ""));
}
O/P :
'100','200','300','400'
或者(如果你不想使用 replaceAll()
两次。
public static void main(String[] args) throws Exception {
String s = "100-200-300-400";
s = s.replaceAll("(\d+)(-|$)", "'',");
System.out.println(s.substring(0, s.length()-1));
}