Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding characters conditionally to a regular expression match

I am using regular expressions in Eclipse, and was wondering whether there's a way to add characters based on the matches.

I am using these expressions to match and replace:

Match: ^(\s*)(//)?(.*?)"([\p{Punct}\p{Space}]*)?(\p{Alnum}.*?\p{Alnum})([\p{Punct}\p{Space}]*)?"(.*?)$
Replace: $1$3"$4" \+ i18n.tr\("$5"\) \+ "$6"$7

For example

System.err.println("Unexpected number of guests: ");

I am trying to replace this with

System.err.println(i18n.tr("Unexpected number of guests") + ": ");

But I am getting

System.err.println("" + i18n.tr("Unexpected number of guests") + ": ");

Is there any way to get rid of the "" + preceding i18n.tr(.*) if there's nothing captured?

like image 865
tommoyang Avatar asked Mar 21 '26 13:03

tommoyang


1 Answers

You can't do this with a single search-replace!

The only way is to use two search-replace:

  • the first with the punct-space

Match: ^(\s*)(//)?(.*?)"([\p{Punct}\p{Space}]++)(\p{Alnum}.*?\p{Alnum})([\p{Punct}\p{Space}]*)?"(.*?)$

Replace: $1$3"$4" \+ i18n.tr\("$5"\) \+ "$6"$7

  • second without the punct-space

Match: ^(\s*)(//)?(.*?)"(\p{Alnum}.*?\p{Alnum})([\p{Punct}\p{Space}]*)?"(.*?)$

Replace: $1$3i18n.tr\("$4"\) \+ "$5"$6

Don't forget to do a backup before any tries

like image 75
Casimir et Hippolyte Avatar answered Mar 24 '26 03:03

Casimir et Hippolyte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!