开发者

Prepending string using replaceAll and regex

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜