append使用regex替换为重复模式

sf6xfgos  于 2021-07-12  发布在  Java
关注(0)|答案(2)|浏览(286)

我需要在java程序中附加/替换以下模式。
原始字符串:

{ "values" : ["AnyValue1", "TestValue", "Dummy", "SomeValue"], "key" : "value" }

[编辑:此值数组中可以有n个值]
我需要用“\u val”附加所有值

{ "values" : ["AnyValue1_val", "TestValue_val", "Dummy_val", "SomeValue_val"], "key" : "value" }

我想知道我是否可以用regex替换而不是遍历循环?
内容位于字符串中:

String content = "{ \"values\" : [\"AnyValue1\", \"TestValue\", \"Dummy\", \"SomeValue\"], \"key\" : \"value\" }";
zysjyyx4

zysjyyx41#

我已经研究你的问题好几分钟了。我想出了一个解决办法。它可能不是最好的,因为我不太习惯使用regex。

概念

这是一个两步解决方案:

1st step: Obtain the substring between [...] using regex.
2nd step: Obtain all the substring between "..." and append "_val" in the end.

我们需要首先获得[…]之间的子串的原因是,如果我们直接应用第二步,那么“values”、“key”和“value”也会改变。这不是你想要的。

代码

//Set the string
String str = "{ \"values\" : [\"AnyValue1\", \"TestValue\", \"Dummy\", \"SomeValue\"], \"key\" : \"value\" }";

//Set the first pattern to find the substring between [...]
Pattern pattern1 = Pattern.compile("(?<=\\[).*(?=])");
Matcher matcher1 = pattern1.matcher(str);

if (matcher1.find())
{
    String values = matcher1.group();

    //Set the first pattern to find all the substring between "..."
    Pattern pattern2 = Pattern.compile("(?<=\")[a-zA-z0-9]+(?=\")");
    Matcher matcher2 = pattern2.matcher(values);

    while (matcher2.find())
    {
        str = str.replace(matcher2.group(), matcher2.group()+"_val");
    }

    System.out.println(str);
}

输出

{ "values" : ["AnyValue1_val", "TestValue_val", "Dummy_val", "SomeValue_val"], "key" : "value" }

我希望我帮助过你。未来可能会有更好的方法 java.util.regex.Pattern 或者 java.util.regex.Matcher 可以更轻松地完成任务的类。也许它们可以在一个命令中替换所有的子字符串。但是,我不经常使用这些类,所以我不熟悉它。
如果您对所使用的正则表达式有任何疑问,或者如果有人想对我的答案提出任何改进,请发表评论。

9ceoxa92

9ceoxa922#

试试这个。

String content = "{ \"values\" : [\"AnyValue1\", \"TestValue\", \"Dummy\", \"SomeValue\"], \"key\" : \"value\" }";
Pattern bracket = Pattern.compile("\\[.*?\\]");
Pattern string = Pattern.compile("\"(.*?)\"");
String result =  bracket.matcher(content)
    .replaceAll(m -> string.matcher(m.group())
        .replaceAll(n -> "\"" + n.group(1) + "_val\""));
System.out.println(result);

输出:

{ "values" : ["AnyValue1_val", "TestValue_val", "Dummy_val", "SomeValue_val"], "key" : "value" }

相关问题