2013-04-05 67 views
0

可能用java中的String替换字符,使用匹配指令中的特定字符。用正则表达式替换其他索引的字符?

例如:

我想使用一些特定的地图:

一个= d,B = E,C = F

然后:一个要与d取代的a,b与e和c与f。

这是代码的理念:

String src = "text_abc"; 
    String regex = "a|b|c"; 
    String replacement = "d|e|f"; 
    String replaced = src.replace(regex, replacement); 

我不知道是什么的正则表达式我应该在正则表达式和更换使用的做到这一点。

回答

1

对于这种情况,您可以使用String.replace(char, char)

String src = "text_abc"; 
String replaced = src.replace('a', 'd') 
        .replace('b', 'e') 
        .replace('c', 'f'); 

如果你坚持使用正则表达式(这是这种情况下,一个愚蠢的想法,这是低效的和不必要的不​​可维护的),你可以使用一个Map相应的查找替换:

String src = "text_abc"; 

// Can move these to class level for 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); 

这是online code demo

1

你为什么不这样做呢?

String replaced = src.replace("a", "d").replace("b", "e").replace("c", "f"); 

还要注意的是使用正则表达式,你需要使用replaceAll()replace()

+0

谢谢,但可以做到白衣正则表达式吗? – carlos 2013-04-05 19:33:51