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||"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With