11

我有以下Java SE代码,可在 PC 上运行

public static void main(String[] args) {
    // stringCommaPattern will change
    // ","abc,def","
    // to
    // ","abcdef","        
    Pattern stringCommaPattern = Pattern.compile("(\",\")|,(?=[^\"[,]]*\",\")");
    String data = "\"SAN\",\"Banco Santander, \",\"NYSE\"";
    System.out.println(data);
    final String result = stringCommaPattern.matcher(data).replaceAll("$1");
    System.out.println(result);
}

我得到了预期的结果

"SAN","Banco Santander, ","NYSE"
"SAN","Banco Santander ","NYSE"

但是,当谈到Android时。

Pattern stringCommaPattern = Pattern.compile("(\",\")|,(?=[^\"[,]]*\",\")");
String data = "\"SAN\",\"Banco Santander, \",\"NYSE\"";
Log.i("CHEOK", data);
final String result = stringCommaPattern.matcher(data).replaceAll("$1");
Log.i("CHEOK", result);

我越来越

"SAN","Banco Santander, ","NYSE"
"SAN","Banco Santandernull ","NYSE"

任何建议和解决方法,我如何才能使此代码的行为与 Java SE 相同?


附加说明:

其他模式也产生相同的结果。看来,Android 对不匹配的组使用空字符串,而 Java SE 对不匹配的组使用空字符串。

采取以下代码。

public static void main(String[] args) {
    // Used to remove the comma within an integer digit. The digit must be located
    // in between two string. Replaced with $1.
    //
    // digitPattern will change
    // ",100,000,"
    // to
    // ",100000,"        
    final Pattern digitPattern = Pattern.compile("(\",)|,(?=[\\d,]+,\")");
    String data = "\",100,000,000,\"";
    System.out.println(data);
    final String result = digitPattern.matcher(data).replaceAll("$1");
    System.out.println(result);
}

Java SE

",100,000,000,"
",100000000,"

安卓

",100,000,000,"
",100null000null000,"
4

1 回答 1

3

不是原因,但作为一种解决方法,您可以自己执行appendReplacement循环而不是使用replaceAll

StringBuffer result = new StringBuffer();
Matcher m = digitPattern.matcher(data);
while(m.find()) {
  m.appendReplacement(result, (m.group(1) == null ? "" : "$1"));
}
m.appendTail(result);

这应该适用于 JavaSE 和 Android。

或者通过更改正则表达式完全回避问题

Pattern commaNotBetweenQuotes = Pattern.compile("(?<!\"),(?!\")");
String result = commaNotBetweenQuotes.matcher(data).replaceAll("");

在这里,正则表达式只匹配您想要更改的逗号,而不是您想要保持不变的逗号,因此您可以将它们全部替换""为无需捕获组。

于 2013-03-29T09:17:31.930 回答