Home > Software design >  Match expressions for different postfix and suffix
Match expressions for different postfix and suffix

Time:09-16

I am trying to replace part of a String if the value is within % symbols.

So for example the following String.

other text%original text%other text

After replacing it, I should get

other textreplaced textother text

I am able to achieve this via the following:

String newStr = "other text%original text%other text".replaceFirst("%.*%", "replaced text");

But the % symbol is not always guaranteed to come in as %. It might be in ASCII format as follows.

other text%original text%other text

Now I could write it twice like the following.

String toBeReplaced = //

String newStr = toBeReplaced.replaceFirst("%.*%", "replaced text");
newStr = "other toBeReplaced.replaceFirst("%.*%", "replaced text");

But is there a way I could modify the regex so that I can just perform the replacement once to cover both scenarios?

Thank you.

CodePudding user response:

Try this regex in java, other textreplaced textother text is the result.

String str1 = "other text%original text%other text";
System.out.println(str1.replaceAll("\\%.*?%", "replaced text"));

String str2 = "other text%original text%other text";
System.out.println(str2.replaceAll("\\%.*?%", "replaced text"));


System.out.println(str1.replaceAll("(\\%.*?%)|(\\\\%.*?%)", "replaced text"));
  • Related