Java:将一组字符替换为其他不同的字符 [英] Java: replace a set of characters with other different characters

查看:158
本文介绍了Java:将一组字符替换为其他不同的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该做一个自定义装饰器,所以我可以在控制台和文件的输入中替换:

I am supposed to make a custom decorator so I can replace both in an input from console and from a file:


  1. 具有特定字符的字符(例如 char [] x = {'a','b'} code>,因此 a b 成为 *

  2. 一组字符与另一组配对字符(例如 char [] x = {'a','b'} char [] y = {'c','d'} ,所以 a 变为 c b 变为 d

  1. A set of chars with a specific character (e.g. char[] x = {'a', 'b'} with char y = '*', so both a and b become *
  2. A set of chars with another set of paired chars (e.g. char[] x = {'a', 'b'} with char[] y = {'c', 'd'}, so a becomes c and b becomes d

最好的方法是什么?我使用正则表达式( String replaceAll = s.replaceAll(有没有办法在一个正则表达式中使第二种情况?我应该做一个HashMap(第二种情况) ?

What would be the best approach for it? I made the first one with a regular expression ( String replaceAll = s.replaceAll("(a|b)", String.valueOf(replacement)); ), but this wouldn't work for the second case. Is there a way to make the second case in one regex? Should I do a HashMap ?

推荐答案

首先在替换字符及其替换之间创建某种映射会更容易。我的意思是像

It would be easier to first create some kind of mapping between replace character and its replacement. I mean something like

Map<String, String> map = new HashMap();
map.put("a","c");
map.put("b","d");

那么你可以使用 appendReplacement appendTail 从Matcher类中替换匹配的字符。决定如何获取替换字符可以像 map.get(matchedCharacter)

then you can use appendReplacement and appendTail from Matcher class to replace matched character. Deciding on how to get replaced character can be done like map.get(matchedCharacter).

简单演示



Simple Demo

Map<String, String> map = new HashMap();
map.put("a","c");
map.put("b","d");

String demo = "abcdef";
Pattern p = Pattern.compile("[ab]");
Matcher m = p.matcher(demo);
StringBuffer sb = new StringBuffer();
while (m.find()){
    m.appendReplacement(sb, map.get(m.group()));
}
m.appendTail(sb);

System.out.println(sb);

输出: cdcdef

这篇关于Java:将一组字符替换为其他不同的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆