java - Replace with regular expression a character with other by index? -
is possible replace character in string in java, using specific character indice of match.
for example:
i want use specific map:
a=d , b=e , c=f
then: want replace d, b e , c f.
this idea of code:
string src = "text_abc"; string regex = "a|b|c"; string replacement = "d|e|f"; string replaced = src.replace(regex, replacement);
i don't know regular expression should use in regex , replacement this.
you can use string.replace(char, char)
case.
string src = "text_abc"; string replaced = src.replace('a', 'd') .replace('b', 'e') .replace('c', 'f');
if insist on using regular expressions (which silly idea case, it's inefficient , unnecessarily unmaintainable), can use map
corresponding look-up replacement:
string src = "text_abc"; // can move these class level reuse. final hashmap<string, string> map = new hashmap<>(); map.put("a", "d"); map.put("b", "e"); map.put("c", "f"); final pattern pattern = pattern.compile("[abc]"); string replaced = src; matcher matcher; while ((matcher = pattern.matcher(replaced)).find()) replaced = matcher.replacefirst(map.get(matcher.group())); // system.out.println(replaced);
here online code demo.
Comments
Post a Comment