在特定格式的两个字符串之间添加逗号分隔符

时间:2019-07-02 23:15:03

标签: java regex

具有两个特定格式的字符串。需要使用正则表达式在两个字符串之间添加逗号。

   String input1 = "\"abc_xyz\"";
   String input2 = "\"ijk_bcd\"";
   String result = (input1+input2).replaceAll("([^ ]) ", "$1,");

使用上述正则表达式,我得到的结果为

"abc_xyz" "ijk_bcd". 
Expected output should look like 
"abc_xyz","ijk_bcd".

2 个答案:

答案 0 :(得分:0)

我的猜测是,该表达式也可以解决问题,但这不是必需的:

(.*")(".*)

Demo

测试

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "(.*\")(\".*)";
final String string = input1+input2;
final String subst = "$1,$2";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);

System.out.println("Substitution result: " + result);

答案 1 :(得分:0)

你可以做

String joinedString = String.join(",", input1, input2);