开发者

Prepending string using replaceAll and regex

开发者 https://www.devze.com 2023-02-14 22:03 出处:网络
I can\'t figure out how to create regular expression using positiv开发者_开发知识库e lookahead. The idea is to prepend two character string to every two character in a long string. i.e.

I can't figure out how to create regular expression using positiv开发者_开发知识库e lookahead. The idea is to prepend two character string to every two character in a long string. i.e.

"090909" => "XX09XX09XX09"

This code:

String s = "090909";
String ns = s.replaceAll("(?=\\d\\d)", "XX");  

...doesn't work; the output is XX0XX9XX0XX9XX09. But this code works:

String s = "090909";
String ns = s.replaceAll("(?=09)", "XX");  

I'm confused on how to come up with an expression saying lookahead for every two characters. Am I missing some boundaries or something?


You can use the following:

String s = "090909";
String ns = s.replaceAll("(\\d\\d)", "XX$1");  

The ( and ) will create the capture, and the $1 accesses the capture.

0

精彩评论

暂无评论...
验证码 换一张
取 消