Basit
Basit

Reputation: 8606

How to remove matched words from string

Suppose I have a string and I want to check if it contains the following words, then matched words should be removed.

The words are ‘PTE’, ‘LTD’, ‘PRIVATE’ and ‘LIMITED’

I want to check it for both scenerios like if I have word.

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

then output should be just Basit.

and if I have string like:

String company = "xxxBasitxxxMasoodxxx";

then output should be:

BasitMasood

How can I do it?

Thanks

Upvotes: 3

Views: 217

Answers (4)

Ilya
Ilya

Reputation: 29693

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

Upvotes: 0

Kai
Kai

Reputation: 39641

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

will result in

BasitMasood

Upvotes: -1

PermGenError
PermGenError

Reputation: 46418

Use String#replaceAll(regex, str)

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

output:

Basit

Upvotes: 1

Maroun
Maroun

Reputation: 95968

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

Upvotes: 1

Related Questions