regex with replaceAll

时间:2017-06-12 17:00:59

标签: java

I have done some searching and would like advice on this problem:

I want to replace "labels":"Webapp" with "labels":["Webapp"]

I found the regex (\"labels\"\:\")+(([a-zA-Z]|\s|\-)+)+(\") with the following substitution "labels":["$2"]

I use the method replaceAll and the Talend editor.

I write output_row.json = output_row.json.replaceAll("(\"labels\"\:\")+(([a-zA-Z]|\s|\-)+)+(\")",""labels":["$2"]"); but It doesn't work.

Message détaillé: Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \ )

Then I escaped the characters, I did:

output_row.json = output_row.json.replaceAll("(\\"labels\\"\:\\")+(([a-zA-Z]|\\s|\-)+)+(\\")","\"labels\":[\"$2\"]");

But It doesn't work yet.

Please could you help me?

Thanks.

1 个答案:

答案 0 :(得分:2)

问题:不要逃避-:他们不是regex

中的特殊字符

\s一起转义\\s加上转义",就像您在第二个示例中所做的那样\"labels\":[\"$2\"]

虽然您可以使用更简洁的正则表达式并将\\s-合并到character class []

您可以使用(\"labels\":\")+([a-zA-Z -]+)\

System.out.println("labels\":\"Webapp"
        .replaceAll("(\"labels\":\")+([a-zA-Z -]+)\""
                , "\"labels\":[\"$2\"]"));