简体   繁体   English

有条件地将字符添加到正则表达式匹配

[英]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. 我在Eclipse中使用正则表达式,并想知道是否有一种方法可以根据匹配添加字符。

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? 如果没有捕获任何东西,有没有办法摆脱“+ +前面的i18n.tr(。*)?

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 不要忘记在任何尝试之前进行备份

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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