Java:将一组字符替换为其他不同的字符 [英] Java: replace a set of characters with other different characters
问题描述
我应该做一个自定义装饰器,所以我可以在控制台和文件的输入中替换:
I am supposed to make a custom decorator so I can replace both in an input from console and from a file:
- 具有特定字符的字符(例如
char [] x = {'a','b'}
code>,因此a
和b
成为*
- 一组字符与另一组配对字符(例如
char [] x = {'a','b'}
与char [] y = {'c','d'}
,所以a
变为c
和b
变为d
- A set of chars with a specific character (e.g.
char[] x = {'a', 'b'}
withchar y = '*'
, so botha
andb
become*
- A set of chars with another set of paired chars (e.g.
char[] x = {'a', 'b'}
withchar[] y = {'c', 'd'}
, soa
becomesc
andb
becomesd
最好的方法是什么?我使用正则表达式( 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屋!