Jake Wagner
Jake Wagner

Reputation: 826

Replace multiple strings altogether

I have this situation where I have to replace multiple strings with a single string value.

String replacedString = Information.replace("", "Resident Referral").
replace("", "Return Visitor");

Referral                 
Resident Referral          
Resident Referrral  -------------- Replace all three with Resident Referral

Return visitor
Return Visitor
Return Vistitor
Return Vistor    ----------------- Replace all four with Return Visitor

Replace the string values where Refer is common with Resident Referral and replace the string values where Return is common with Return Visitor.

How can I get this done?

Upvotes: 0

Views: 360

Answers (1)

Max van Deursen
Max van Deursen

Reputation: 60

As far as I understand, you want Referral, Resident Referral and Resident Referrral to be replaced with Resident Referral, as well as Return visitor, Return Visitor, Return Vistitor and Return Vistor to be replaced with Return Visitor

The way to go is to use Regular Expressions in order to match all cases with one expression.
An example for the Regular Expressions to use would be Information.replaceAll("(Resident )?Refer{1,3}al", "Resident Referral") for the replacing each case with Resident Referral and Information.replaceAll("Return [Vv]isi?ti?t?or", "Return Visitor") for replacing each case with Return Visitor.

Please note that my knowledge on Regular Expressions is quite basic and these might not be the most efficient or beautiful ways of expressing these cases in Regular Expressions.

Moreover, I have found that RegExr is quite a nice website to get yourself familiar with the usage of Regular Expressions, as well as practicing with Regular Expressions yourself.

Upvotes: 1

Related Questions