简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM