简体   繁体   English

用于字符串的Java replaceALL

[英]Java replaceALL for string

I have a string: 我有一个字符串:

100-200-300-400

i want replace the dash to "," and add single quote so it become: 我想将短划线替换为“,”并添加单引号,使其成为:

 '100','200','300','400'

My current code only able to replace "-" to "," ,How can i plus the single quote? 我目前的代码只能将“ - ”替换为“,”,我怎么能加上单引号?

String str1 = "100-200-300-400";      
split = str1 .replaceAll("-", ",");

if (split.endsWith(",")) 
{
   split = split.substring(0, split.length()-1);
}

You can use 您可以使用

split = str1 .replaceAll("-", "','");
split = "'" + split + "'";

As an alternative if you are using java 1.8 then you could create a StringJoiner and split the String by - . 作为替代,如果您使用的是Java 1.8,那么您可以创建一个StringJoiner并将String拆分为- This would be a bit less time efficient, but it would be more safe if you take, for example, a traling - into account. 这将是一个少一点时间效率,但是如果考虑,例如,traling这将是更安全的-考虑在内。

A small sample could look like this. 一个小样本可能看起来像这样。

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);

This will work for you : 这对你有用:

public static void main(String[] args) throws Exception {
    String s = "100-200-300-400";
    System.out.println(s.replaceAll("(\\d+)(-|$)", "'$1',").replaceAll(",$", ""));
}

O/P : O / P:

'100','200','300','400'

Or (if you don't want to use replaceAll() twice. 或者(如果您不想两次使用replaceAll()

public static void main(String[] args) throws Exception {
    String s = "100-200-300-400";
    s = s.replaceAll("(\\d+)(-|$)", "'$1',");
    System.out.println(s.substring(0, s.length()-1));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM