简体   繁体   English

我怎样才能替换 Java 中某个单词的所有实例,只要它们不是其他单词的一部分?

[英]How can I replace all instances of a word in Java as long as they're not part of other words?

I'm a beginner in Java and wanted to ask how we can replace the word "is" in a string with "is not" only while it's not preceded by or followed by another letter (numbers and symbols fine) and isn't a part of another word.我是 Java 的初学者,想问一下我们如何才能将字符串中的单词“is”替换为“is not”,前提是它前面或后面没有另一个字母(数字和符号都可以)并且不是另一个词的一部分。

For example, I want to replace the word "is" with "is not" in every string, but it's difficult to do so without changing all words that contain "is" such as "this" or "miss".例如,我想在每个字符串中将单词“is”替换为“is not”,但如果不更改所有包含“is”的单词(例如“this”或“miss”),则很难做到这一点。

Currently, my code gets stuck in an infinite loop when I try to use a word like "this" to call it.目前,当我尝试使用像“this”这样的词来调用它时,我的代码陷入了无限循环。 (see example outputs below) For example, here is my code: (参见下面的示例输出)例如,这是我的代码:

public static String isReplace(String str) {
    String newStr = "";
    for (int i = 0; i < str.length(); i++) {
        
        if (str.charAt(i) == ('i') && str.charAt(i + 1) == ('s')) {
            if (!(Character.isLetter(str.charAt(i + 2)))) {
                str = str.replace("is", "is not");
            }
        }
        //break;
    }
    return str ; // FIX ME
}

isReplace("This is good")); //should give me "This is not good"

isReplace("is-is")); //should give me "is not-is not"
isReplace("My favorite food is9ie")) // should give me "My favorite food is not9ie"

Just added more refinement over your existing logic.只是对您现有的逻辑进行了更多改进。

public class P1 {

    public static String isReplace(String str) {

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {

            char current = str.charAt(i);

            //if last character just add it to the buffer
            if(i == str.length()-1){
                sb.append(current);
            }else{
                char next = str.charAt(i+1);
                if(current == 'i' && next == 's'){
                    //check is preceding character is not letter and following character is not letter
                    if((i == 0 || !Character.isLetter(str.charAt(i-1))) &&
                            ((i+2 == str.length() || !Character.isLetter(str.charAt(i+2))))){
                        sb.append("is not");
                        i++;  // to skip reading s in next iteration
                    }else{
                        sb.append(current);
                    }
                }else{
                    sb.append(current);
                }
            }
        }
        return sb.toString() ;
    }

    public static void main(String[] args) {
        System.out.println(isReplace("This is good"));
        System.out.println(isReplace("is-is"));
        System.out.println(isReplace("My favorite food is9ie"));
    }
}
This is not good
is not-is not
My favorite food is not9ie

Probably the easiest method is to use Regex.可能最简单的方法是使用正则表达式。 With this search input, it searches for all "is" that are not surrounded by letters.使用此搜索输入,它会搜索所有未被字母包围的“是”。

str.replaceAll("(?<![a-zA-Z])is(?![a-zA-Z])", "is not")

Here is a working example:这是一个工作示例:

  public class Main {

  public static String isReplace(String string) {
    return string.replaceAll("(?<![a-zA-Z])is(?![a-zA-Z])", "is not");
  }

  public static void main(String[] args) {
    System.out.println(isReplace("This is good"));
    System.out.println(isReplace("My favorite food is9ie"));
    System.out.println(isReplace("is#is"));
  }
}

Output: Output:

This is not good
is not#is not
My favorite food is not9ie

Regex explained:正则表达式解释:

  (        Open the first capturing group
  ?<!      Negative lookbehind. This will look before the search results and check that none of the following characters are there.
  [a-zA-Z] Character set of all letters.
  )        Close the first capturing group.
  is       Searches for "is".
  (        Open the second capturing group.
  ?!       Negative lookahead. This will look ahead of the search results and check that none of the following characters are there.
  [a-zA-Z] Character set of all letters.
  )        Close the second capturing group.

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

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