当前位置: 动力学知识库 > 问答 > 编程问答 >

regex - Java Replace particular positioned delimiter with another delimeter

问题描述:

Given this line:

String name="Summer,John,Alex,Stu,Mike,will,King,yahoo,Google,jeff";

I want to replace comma with || symbol after every 4th occurrence of the comma.

Expected output:

Summer,John,Alex,Stu||Mike,will,King,yahoo||Google,jeff

I have done this in awk command

awk -F, '{

for (i=1; i<NF; i++)

printf "%s%s", $i, (i%4?FS:"||");

print $i

}'

I am unable to convert this command into java regex.

网友答案:

You can try this,

String name="Summer,John,Alex,Stu,Mike,will,King,yahoo,Google,jeff";
System.out.println(name.replaceAll("(\\w+,\\w+,\\w+,\\w+),", "$1||"));

OUTPUT

Summer,John,Alex,Stu||Mike,will,King,yahoo||Google,jeff

Note : \\w+ means one or more word characters and $1 stands for group 1

EDIT :

what if i want to replace 100th position? do i need to use 100 \w+?

Not really you can use grouping here again and specify {} count of occurrence of group something like,

String name="Summer,John,Alex,Stu,Mike,will,King,yahoo,Google,jeff,test,hell,";
System.out.println(name.replaceAll("((\\w+,){3}(\\w+)),", "$1||"));
分享给朋友:
您可能感兴趣的文章:
随机阅读: