Nouvel Travay
Nouvel Travay

Reputation: 6472

How to apply two regex back to back

Say I have regex1 and regex2. I want to apply regex1 to text1 and then apply regex2 to the result. Is there a way of during this without using the java method twice?

I know I can do

text1 = text1.replaceAll(regex1,””).replaceAll(regex2,””);

But is there a way to do it all in one method call? Like

text1 = text1.replaceAll(regex1+"|"+ regex2,””);//this of course does not work

Upvotes: 0

Views: 56

Answers (1)

Andreas
Andreas

Reputation: 159114

No way to automatically combine two chained replaceAll(regex,"") into a single replaceAll(regex,"").

Example of why not: "bob".replaceAll("o","").replaceAll("bb","").
The second only removes the two b's if the first has removed the o.

You can manually merge them, because you can see how they might interact, e.g. "bob".replaceAll("o|bo*b",""), but combining two arbitrary regex's is not possible.

Upvotes: 1

Related Questions