简体   繁体   English

如何在 Java 中查找和替换字符串中所有出现的子字符串?

[英]How find and replace all occurrences of substring in string in Java?

I looked at the existing topics, but my task is slightly different from those on the forum.我查看了现有主题,但我的任务与论坛上的任务略有不同。 I have the value:我有以下价值:

int j = 37;

And I have one of the strings:我有一个字符串:

1) String s1 = "5+2+5+2 --j *2*7+3";
2) String s1 = "5+2+5+2 j-- *2*7+3";
3) String s1 = "5+2+5+2 ++j *2*7+3";
4) String s1 = "5+2+5+2 j++ *2*7+3";

I need with regular expression find --j , j-- , ++j , j++ and replace this occurrences of substring in string with number value j ;我需要用正则表达式找到--jj--++jj++和替换此事件中的字符串数值串的j ;

Result string must be like this:结果字符串必须是这样的:

1) 5+2+5+2 36 *2*7+3
2) 5+2+5+2 36 *2*7+3
3) 5+2+5+2 38 *2*7+3
4) 5+2+5+2 38 *2*7+3

With pattern str.split(search).join(replacement) I can replace the char j with number 37 :使用模式str.split(search).join(replacement)我可以用数字37替换字符j

str.split("j").join(37);

Then I get:然后我得到:

1) String s1 = "5+2+5+2 --37 *2*7+3";
2) String s1 = "5+2+5+2 37-- *2*7+3";
3) String s1 = "5+2+5+2 ++37 *2*7+3";
4) String s1 = "5+2+5+2 37++ *2*7+3";

Question:题:
But how to perform the arithmetic operation ( increment , decrement ) at this time?但是此时如何进行算术运算( incrementdecrement )呢?

public class Test
{
    public static void main(String[] args)
    {
        int j = 37;
        String s1 = "5+2+5+2 ++j *2*7+3";
        
        // this line swap "j--" or "--j" on j--
        s1 = s1.replaceAll("j--|--j", j-1 + "");
        
        // this line swaps "j++" or "++j" on j++
        s1 = s1.replaceAll("(j\\+\\+)|(\\+\\+j)", j+1 + "");
        
        System.out.println(s1);
    }
}

String.replaceAll may be used as follows: String.replaceAll可以按如下方式使用:

int j = 37;
String[] d = {
    "5+2+5+2 --j *2*7+3",
    "5+2+5+2 j-- *2*7+3",
    "5+2+5+2 ++j *2*7+3",
    "5+2+5+2 j++ *2*7+3"
};
        
Arrays.stream(d)
      .map(s -> s.replaceAll("--j|j--", Integer.valueOf(j - 1).toString()))
      .map(s -> s.replaceAll("\\+\\+j|j\\+\\+", Integer.valueOf(j + 1).toString()))
      .forEach(System.out::println);

to provide expected output:提供预期输出:

5+2+5+2 36 *2*7+3
5+2+5+2 36 *2*7+3
5+2+5+2 38 *2*7+3
5+2+5+2 38 *2*7+3

Note that in the question, the operations do not follow the Java behaviour, ie pre- and postincrement both behave like preincrement.请注意,在问题中,操作不遵循 Java 行为,即前增量和后增量都像前增量一样。

To implement this behaviour, we need two regular expressions:为了实现这种行为,我们需要两个正则表达式:

  • One expression matching all --j and j-- to replace them with the value of j - 1 :一个表达式匹配所有--jj--用的值来取代它们j - 1

    [-]{2}j|j[-]{2} Regex101 demo [-]{2}j|j[-]{2} Regex101 演示

  • One expression matching all ++j and j++ to replace them with the value of j + 1 :一个匹配所有++jj++表达式以将它们替换为j + 1的值:

    [+]{2}j|j[+]{2} Regex101 demo [+]{2}j|j[+]{2} Regex101 演示

Putting it together, we can write the following method:综合起来,我们可以写出如下方法:

public static String replaceJWith(String s, int valueForJ) {
    s = s.replaceAll("[-]{2}j|j[-]{2}", Integer.toString(valueForJ - 1));
    return s.replaceAll("[+]{2}j|j[+]{2}", Integer.toString(valueForJ + 1));
}

Ideone demo Ideone 演示

This implementation assumes that each occurrence of j is pre- or suffixed by ++ or -- .此实现假定j每次出现都以++--为前缀或后缀。 Also, since we never really change the value of j , using multiple pre-, and postincrement operators in a single String will result in unexpected behaviour.此外,由于我们从未真正更改j的值,因此在单个String使用多个前增量和后增量运算符将导致意外行为。


If we want to mimic the Java behaviour (ie distinguish between pre- and postincrement), we need three different regular expressions since we have to replace j with three different values:如果我们想模仿 Java 行为(即区分前后增量),我们需要三个不同的正则表达式,因为我们必须用三个不同的值替换j

  • One regex to replace j(++|--) with the original value for j :一个正则表达式来代替j(++|--)与原始值j

    j(?:[+]{2}|[-]{2}) Regex101 demo j(?:[+]{2}|[-]{2}) Regex101 演示

  • One regex to replace ++j with the value j + 1 :一个用值j + 1替换++j正则表达式:

    [+]{2}j Regex101 demo [+]{2}j Regex101 演示

  • One regex to replace --j with the value j - 1 :用值j - 1替换--j一个正则表达式:

    [-]{2}j Regex101 demo [-]{2}j Regex101 演示

Setting it all together, we can write the following Java method:将所有这些设置在一起,我们可以编写以下 Java 方法:

public static String replaceJWith(String s, int valueForJ) {
    s = s.replaceAll("j(?:[+]{2}|[-]{2})", Integer.toString(valueForJ));
    s = s.replaceAll("[+]{2}j", Integer.toString(valueForJ + 1));
    return s.replaceAll("[-]{2}j", Integer.toString(valueForJ - 1));
}

Ideone demo Ideone 演示

This solution has the same limitations as the first solution.此解决方案与第一个解决方案具有相同的限制。

You can use a series of if statements that check the string for the presence of each of those patterns using contains() and then replace the pattern with the corresponding value:您可以使用一系列if语句,使用contains()检查字符串中每个模式是否存在,然后将模式替换为相应的值:

if (s1.contains("--j") {
  s1.replace("--j", String.valueOf(j-1)); //assuming you have declared int j = 37; before 
} else if (s1.contains("j--")) { 
  //etc.
} [...]

暂无
暂无

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

相关问题 在Java中查找字符串中出现的所有子字符串 - Find all occurrences of substring in string in Java 替换字符串中出现的所有子字符串 - 这在Java中更有效吗? - Replace all occurrences of substring in a string - which is more efficient in Java? 如何查找给定字符串中所有出现的子字符串(允许使用通配符) - How to find all occurrences of a substring (with wildcards allowed) in a given String 查找字符串中所有出现的分割子字符串 - Find all occurrences of a divided substring in a string 替换所有出现的“;;” 在 Java 中的字符串中 - Replace all occurrences of “;;” in a string in Java 如何使用 Java string replaceAll 将字符串中所有出现的“替换为\” - How to use Java string replaceAll to replace all occurrences of " in a string to \" 如何从字符串中删除所有出现的 substring - How to remove all occurrences of a substring from a string 如何用Java中的参数替换子字符串的所有出现? - how to substitute all occurrences of a substring with parameters in Java? 如何在 java 中使用正则表达式替换标签 &lt;&gt; 中所有出现的字符串 - how to replace all occurrences of a string inside tags <> using regex in java java - 如何使用模式和匹配器在java中查找子字符串=&quot;\\\\r&quot; in a string=&quot;This is a \\\\\\\\rtest \\\\n\\\\r string&quot; 的出现 - How to find occurrences of a substring="\\r" in a string="This is a \\\\\rtest \\n\\r string" in java using Pattern and matchers
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM