Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Replace particular positioned delimiter with another delimeter

Tags:

java

string

regex

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.

like image 462
user952977 Avatar asked Dec 20 '22 00:12

user952977


1 Answers

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||"));
like image 193
akash Avatar answered Dec 25 '22 23:12

akash