简体   繁体   English

在java中替换字符串中的单词

[英]Replace word from string in java

String[] operatorList = { "name", "first_name", "last_name", "city" };
String originalString = "city=Houston^ORlast_name=Cervantsz^ORfirst_name=John^name=don";
for (String opElement : operatorList) {
    if (originalString.contains(opElement)) {
        String tempStr = originalString.replace(opElement, "user." + opElement);
        originalString = tempStr;
    }
}
System.out.println("originalString " + originalString);

Output:输出:

user.city=Houston^ORlast_user.name=Cervantsz^ORfirst_user.name=John^user.name=don user.city=休斯顿^ORlast_user.name=Cervantsz^ORfirst_user.name=John^user.name=don

When i am trying to replace name with "user.name" at that time name from "last_name" is replaced with "last_user.name" and first_name with first_user.name当我尝试用“user.name”替换名称时,“last_name”中的名称替换为“last_user.name”,first_name 替换为 first_user.name

But i want replace "name" with "user.name" and "last_name" with "user.last_name" and "first_name" with "user.first_name".但我想用“user.name”替换“name”,用“user.last_name”替换“last_name”,用“user.first_name”替换“first_name”。

Any help appreciated.任何帮助表示赞赏。

You can add prefix all key and control that key.您可以添加前缀所有键并控制该键。 Example例子

String[] operatorList = {"name", "first_name", "last_name", "city"};
    String originalString = "city=Houston^ORlast_name=Cervantsz^ORfirst_name=John^ORname=don";
    for (String opElement : operatorList) {
        if (originalString.contains("^OR"+opElement)) {
            String tempStr = originalString.replace(opElement, "user." + opElement);
            originalString = tempStr;
        }
    }
    System.out.println("originalString " + originalString);

If the values you are trying to change are always unique and generated (meaning they are always in the same order), you can simply put your operators in the same order and use replaceLast() instead.如果您尝试更改的值始终是唯一的并且是生成的(意味着它们始终以相同的顺序排列),您可以简单地将您的运算符放在相同的顺序中并使用replaceLast()代替。

A more complete solution would be to determine how the string is constructed.更完整的解决方案是确定字符串的构造方式。 Do all the values have a ^ in front of them?所有值前面都有^吗? Is OR generated for the same values or is it to indicate optional values?. OR是为相同的值生成的还是表示可选值?。 So in the end, what allows you to split the string properly.所以最后,是什么让您可以正确拆分字符串。 Then you can use a Regex to use the surrounding characters.然后您可以使用正则表达式来使用周围的字符。

I would format the string to make sure the splitters are constant (all "^OR" become "@@%!!" and all remaining "^" become "%!!") so all replaced strings start with !!.我会格式化字符串以确保分隔符是恒定的(所有“^OR”变成“@@%!!”,所有剩余的“^”变成“%!!”)所以所有替换的字符串都以!!开头。 Then I would reformat the string to the original format using the remaining "@@%" or "%" :然后我会使用剩余的 "@@%" 或 "%" 将字符串重新格式化为原始格式:

String[] operatorList = { "name", "first_name", "last_name", "city" };
String originalString = "city=Houston^ORlast_name=Cervantsz^ORfirst_name=John^name=don";

originalString = originalString.replaceAll("\\^OR", "@@%!!");
originalString = originalString.replaceAll("\\^", "%!!");
  //the order is important here

for (String opElement : operatorList) {
    if (originalString.startsWith(opElement)) {
        originalString = originalString.replaceFirst(opElement, "user." + opElement);
    }

    originalString = originalString.replaceAll("!!" + opElement, "user." + opElement);
      // no need for an other alternative here because replaceAll returns the
      // String as is if it does not find the first parameter in the String.
}

originalString = originalString.replaceAll("@@%", "^OR");
originalString = originalString.replaceAll("%", "^");
  // the order here is also important

outputs : "user.city=Houston^ORuser.last_name=Cervantsz^ORuser.first_name=John^user.name=don"输出: "user.city=Houston^ORuser.last_name=Cervantsz^ORuser.first_name=John^user.name=don"

If all keypairs need prefix "user.", I would like to split originalString first.如果所有密钥对都需要前缀“user.”,我想先拆分originalString

In Java8在 Java8 中

String originalString = "city=Houston^ORlast_name=Cervantsz^ORfirst_name=John^name=don";
String[] params = originalString.split("\\^");

String result = String.join("^", Arrays.stream(params)
    .map(param -> param.startsWith("OR") ? "ORuser." + param.substring(2) : "user." + param)
    .collect(Collectors.toList()));

System.out.println(result);

It can also be changed to for loop type.它也可以更改为 for 循环类型。

You may use a quick search and replace with an alternation based pattern created dynamically from the search words only when they are preceded with a word boundary or ^ + OR / AND /etc.您可以使用快速搜索并替换为从搜索词动态创建的基于交替的模式,仅当它们前面有词边界或^ + OR / AND / 等时。 operators and followed with a word boundary.运算符,然后是单词边界。 Note that this solution assumes the search words only consist of word chars (letters, digits or _ ):请注意,此解决方案假定搜索词仅包含字符字符(字母、数字或_ ):

String[] operatorList = { "name", "first_name", "last_name", "city" };
// assuming operators only consist of word chars
String pat = "(\\b|\\^(?:OR|AND)?)(" + String.join("|", operatorList) + ")\\b";
String originalString = "city=Houston^ORlast_name=Cervantsz^ORfirst_name=John^name=don";
originalString = originalString.replaceAll(pat, "$1user.$2");
System.out.println(originalString);
// => user.city=Houston^ORuser.last_name=Cervantsz^ORuser.first_name=John^user.name=don

See the Java demo online在线查看Java 演示

The regex will look like正则表达式看起来像

(\b|\^(?:OR|AND)?)(name|first_name|last_name|city)\b

See the regex demo .请参阅正则表达式演示

Details细节

  • (\\b|\\^(?:OR|AND)?) - Group 1: a word boundary \\b or a ^ symbol and an optional substring, OR or AND (you may add more here after | ) (\\b|\\^(?:OR|AND)?) - 第 1 组:单词边界\\b^符号和可选的子字符串ORAND (您可以在|之后添加更多)
  • (name|first_name|last_name|city) - Group 2: any of the search words (name|first_name|last_name|city) - 第 2 组:任何搜索词
  • \\b - a trailing word boundary. \\b - 尾随词边界。

The $1 in the replacement pattern inserts the contents of Group 1 and $2 does the same with Group 2 contents.替换模式中的$1插入组 1 的内容, $2插入组 2 的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM