I have a list of Strings, and would want to replace a few characters of the individual string entry by new string and add to the list. For eg:
List<String> arrayList = new ArrayList<>(); arrayList.add("s=1;n = 001NDA001"); arrayList.add("s=1;n = 001NDA001.INR"); arrayList.add("s=1;n = 001NDA001.INR.val"); String inputValue ="CSV"; for (String string : arrayString) { if(string.contains("NDA")) { arrayList.add(string.replace(string, inputValue));; } } log.info("arrayList : {}",arrayList);
Current output : arrayList : [s=1;n = 001NDA001, s=1;n = 001NDA001.INR, s=1;n = 001NDA001.INR.val, CSV, CSV, CSV]
ExpectedOutput: arrayList : [s=1;n = 001NDA001, s=1;n = 001NDA001.INR, s=1;n = 001NDA001.INR.val, s=1;n = 001CSV001, s=1;n = 001CSV001.INR, s=1;n = 001NDA001.CSV.val]
I believe it can be achieved with regex, and I need some inputs here. Suggestions?
Advertisement
Answer
Use this code for your problem
for (String string : arrayString) { if(string.contains("NDA")) { arrayList.add(string.replace("NDA", inputValue)); } }