如何从字符串中删除匹配的单词

时间:2013-03-07 08:13:30

标签: java string replace

假设我有一个字符串,并且我想检查它是否包含以下单词,那么应该删除匹配的单词。

单词为‘PTE’, ‘LTD’, ‘PRIVATE’ and ‘LIMITED’

我想检查两个场景,如果我有话。

String company = "xxx Basit xxx";  //xxx can be ‘PTE’, ‘LTD’, ‘PRIVATE’ and ‘LIMITED’

然后输出应该只是Basit

如果我有类似的字符串:

String company = "xxxBasitxxxMasoodxxx";

然后输出应该是:

BasitMasood

我该怎么做?

由于

4 个答案:

答案 0 :(得分:1)

String[] str = {"PTE", "LTD", "PRIVATE", "LIMITED"};
String company = "PTE      Basit PTE";
for(int i=0;i<str.length;i++) {
    company = company.replaceAll(str[i], "");
}
System.out.println(company.replaceAll("\\s","")); //remove whitespaces

答案 1 :(得分:1)

使用String#replaceAll(regex, str)

    String company = "PRIVATE Basit PTE";
    System.out.println(company.replaceAll("PTE|LTD|PRIVATE|LIMITED", ""));

输出:

巴斯特

答案 2 :(得分:0)

String company = //your string
company.replaceAll("PTE|LTD|PRIVATE|LIMITED", "");

答案 3 :(得分:-1)

"PTEBasitLTDMasoodPRIVATE".replaceAll("PTE|LTD|PRIVATE|LIMITED","");

将导致

  

BasitMasood