Java替换未被引号括起来的问号

时间:2016-04-14 22:39:19

标签: java regex string replace

我正在用不同的值替换字符串中的问号。

示例:

String: "XYZ(?,?,?)"

Values: [1, 'Text', 0.5]

Result: XYZ(1,'Text', 0.5)

我的Preudo-Code:

String s = "XYZ(?,?,?)";
for(int i = 0; i < array.lengh; i++){
   s = s.replaceFirst("\\?",array[i]);
}

通常情况下效果很好。但有时我在值中有一个问号:值:[1,'Question?',0.5]。然后我的结果是:XYZ(1,'Question0.5', ?)。这是因为该函数替换了之前替换一次迭代的文本的问号。

如何告诉该函数只替换未被引号括起来的问号?什么是正确的正则表达式?

4 个答案:

答案 0 :(得分:2)

如果你不必使用正则表达式或替换,那怎么样?

String s = "XYZ(?,?,?)";
String[] tokens = s.split("\\?");
s = "";
for(int i = 0; i < array.length; i++){
   s += tokens[i] + array[i];
}
s += tokens[array.length];

(编辑:逃避?在正则表达式,长度有一个t,需要在最后一次插入后的部分)

如果可能存在额外的问号,那么这比要插入的值的数量更多,并且您想要像OP代码那样保留额外的值和后面的任何文本,限制{{1 }}:

split

如果问号的数量或结果的总大小(模板字符串加插入)很大,重复的字符串连接表现很差;改为使用String[] tokens = s.split("\\?", array.length+1);

StringBuilder

答案 1 :(得分:1)

您可以先使用%s替换所有问号,然后使用String.format(input, args...)。像这样:

Object[] array = {1, "Test", 0.5};
String s = "XYZ(?,?,?)";

String output = String.format(s.replace("?", "%s"), array);
System.out.println(output);

会给你这个输出:

  

XYZ(1,测试,0.5)

另外,请注意,在您的问题中,您的s.replaceFirst("\\?",array[i]);调用无效,因为在Java字符串中是不可变的,并且字符串上的所有操作(例如replace)都返回一个新的String,您应该使用返回的字符串

另外注意:字符串应该是双引号而不是单引号。

答案 2 :(得分:0)

您可以使用此正则表达式:

String regex = "\\?(?=[^']+$)";  

这个想法是当你致电s.replaceFirst(regex, str)时,第一个"?"之后不会引用引号不能在引号内。

答案 3 :(得分:0)

如下编码的更直接的方法怎么样?

public class Replacer {
    static String replace(String s, String[] values) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0, j = 0; i < s.length(); i ++) {
            char c = s.charAt(i);
            if (c != '?')
                sb.append(c);
            else
                sb.append(values[j++]);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(replace("XYZ(?, ?, ?)", new String[]{"1", "Question?", "0.5"}));
        System.out.println(replace("XYZ(?, ?, ?)", new String[]{"foo", "bar", "baz"}));
    }
}

打印:

XYZ(1, Question?, 0.5)
XYZ(foo, bar, baz)