我有下面的字符串,例如:
O > O §o TEXT §r §o TEXT §r
我需要在§r
字符之后将所有 §r§a
替换为>
。
应该是
O > O §o TEXT §r§a §o TEXT §r§a
结果。
我尝试了> *(\§r)正则表达式,但忽略了> 。
你可以指出我的错误吗?
答案 0 :(得分:1)
最简单的方法是首先将其拆分为两个字符串,然后运行replace
。也就是说,你可以采取
int index = inputString.indexOf('>') + 1;
String first = inputString.subString(0, index);
String second = inputString.subString(index);
String finalString = first + second.replace("§r", "§r§a");
使用纯正则表达式执行此操作将非常困难。
答案 1 :(得分:1)
((?:(?!>).)*>.*?|)(§r)
替换为: $1§r§a
**要更好地查看图像,只需右键单击图像并在新窗口中选择视图
现场演示
https://regex101.com/r/xP8dI5/1
示例文字
§r O > O §o TEXT §r §o TEXT §r
重播后
§r O > O §o TEXT §r§a §o TEXT §r§a
NODE EXPLANATION
----------------------------------------------------------------------
( group and capture to \1:
----------------------------------------------------------------------
(?: group, but do not capture (0 or more
times (matching the most amount
possible)):
----------------------------------------------------------------------
(?! look ahead to see if there is not:
----------------------------------------------------------------------
> '>'
----------------------------------------------------------------------
) end of look-ahead
----------------------------------------------------------------------
. any character except \n
----------------------------------------------------------------------
)* end of grouping
----------------------------------------------------------------------
> '>'
----------------------------------------------------------------------
.*? any character except \n (0 or more times
(matching the least amount possible))
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
) end of \1
----------------------------------------------------------------------
( group and capture to \2:
----------------------------------------------------------------------
§r '§r'
----------------------------------------------------------------------
) end of \2
----------------------------------------------------------------------
答案 2 :(得分:0)
纯正则表达式方法是使用\G
,如下面的
(\G(?!\A)|>)(.*?)§r
,并替换为
$1$2§r§a
<强> Regex Demo
Java代码
System.out.println("O§r §r > O §o TEXT §r §o §r TEXT §r".replaceAll("(\\G(?!\\A)|>)(.*?)§r", "$1$2§r§a"));
<强> Ideone Demo