用另一个替换特定的字符串-String#replaceAll() [英] Replace specific string by another - String#replaceAll()

查看:275
本文介绍了用另一个替换特定的字符串-String#replaceAll()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实际上是在开发一个解析器,并且陷入了一种方法的困境.

I'm actually developping a parser and I'm stuck on a method.

我需要清除某些句子中的特定单词,这意味着用空格或null字符替换这些单词. 现在,我想到了以下代码:

I need to clean specifics words in some sentences, meaning replacing those by a whitespace or a nullcharacter. For now, I came up with this code:

private void clean(String sentence)
{
    try {
        FileInputStream fis = new FileInputStream(
                ConfigHandler.getDefault(DictionaryType.CLEANING).getDictionaryFile());
        BufferedReader bis = new BufferedReader(new InputStreamReader(fis));
        String read;
        List<String> wordList = new ArrayList<String>();

        while ((read = bis.readLine()) != null) {
            wordList.add(read);
        }
    }
    catch (IOException e) {
        e.printStackTrace();
    }

    for (String s : wordList) {
        if (StringUtils.containsIgnoreCase(sentence, s)) { // this comes from Apache Lang
            sentence = sentence.replaceAll("(?i)" + s + "\\b", " ");
        }
    }

    cleanedList.add(sentence);

} 

但是当我查看输出时,我发现sentence中所有要替换的单词都由空格代替.

But when I look at the output, I got all of the occurences of the word to be replaced in my sentence replaced by a whitespace.

有人能帮助我仅替换句子中要替换的确切单词吗?

Does anybody can help me out on replacing only the exact words to be replaced on my sentence?

提前谢谢!

推荐答案

您的代码中存在两个问题:

There are two problems in your code:

  • 您丢失了\b 之前字符串
  • 如果文件中的任何单词带有特殊字符,您都会遇到问题
  • You are missing the \b before the string
  • You will run into issues if any of the words from the file has special characters

要解决此问题,请按如下所示构造您的正则表达式:

To fix this problem construct your regex as follows:

sentence = sentence.replaceAll("(?i)\\b\\Q" + s + "\\E\\b", " ");

sentence = sentence.replaceAll("(?i)\\b" + Pattern.quote(s) + "\\b", " ");

这篇关于用另一个替换特定的字符串-String#replaceAll()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆