[英]How to skip a specific word when replace the String using regexp in java
Consider the string 考虑字符串
String s = "H_ello pe_rfec_t wor_ld"
I want to replace all '_' symbols on... no matter what, let`s say on '1', except those which are placed inside the 'pe_rfec_t'. 我想替换...上的所有“ _”符号,无论如何,让我们说“ 1”,除了那些放置在“ pe_rfec_t”内部的符号。 I could not find any solution even to just skip the word 'pe_rfec_t': 我什至找不到任何解决方案,甚至只是跳过单词“ pe_rfec_t”:
s = s.replaceAll("(?<=pe_rfec_t).*|.*(?=pe_rfec_t)", "1");
looks nice at a glance but results to: 一眼看上去不错,但结果是:
11pe_rfec_t1 //instead of 1111111pe_rfec_t1111111
Ideally I need the following result: 理想情况下,我需要以下结果:
Hello pe_rfec_t world
Could anyone help me please? 有人可以帮我吗?
You can use alternation and captured group: 您可以使用交替和捕获组:
String str = "H_ello pe_rfec_t wor_ld";
String repl = str.replaceAll("(pe_rfec_t)|_", "$1");
//=> Hello pe_rfec_t world
Here in alternation we match first pe_rfec_t
and capture it in group #1. 在这里,我们交替匹配第一个pe_rfec_t
并将其捕获在组#1中。 In repalcement we put $1
(back-reference to group #1) back. 在补给中,我们放回$1
(向第一组的反向引用)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.