Java:用其他不同的字符替换一组字符
我应该做一个自定义装饰器,所以我可以在控制台和文件的输入中替换它们:
- 一组具有特定字符的字符(例如
char[] x = {'a', 'b'}
其中char y = '*'
,因此a
和b
变为*
- 一组具有另一组配对字符的字符(例如
char[] x = {'a', 'b'}
其中char[] y = {'c', 'd'}
,因此a
变为c
,b
变为d
最好的方法是什么? 我用正则表达式创建了第一个( String replaceAll = s.replaceAll("(a|b)", String.valueOf(replacement));
),但这不适用于第二种情况。 有没有办法在一个正则表达式中制作第二个案例? 我应该做一个HashMap吗?
首先在替换字符和替换字符之间创建某种映射会更容易。 我的意思是
Map map = new HashMap(); map.put("a","c"); map.put("b","d");
然后你可以使用appendTail
类中的appendReplacement
和appendTail
来替换匹配的字符。 决定如何获取替换字符可以像map.get(matchedCharacter)
那样完成。
简单的演示
Map 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
DjMike,
对于第二个,在替换期间有用的是调用一个方法,您注入逻辑以用不同的字符串替换不同的字符。
PHP有一个很棒的工具就是这个名为preg_replace_callback()的工具。 链接的答案是关于Java等效于preg_replace_callback()的问题
在这里,这项工作100%正确的任何例子….
public static void main(String[] args) { String test = "My name is Baba"; Character[] x = { 'a', 'b' }; StringBuilder sb = new StringBuilder(); sb.append("("); for (int i = 0; i < x.length; i++) { if (i == (x.length - 1)) { sb.append(x[i] + ")"); } else { sb.append(x[i] + "|"); } } System.out.println(sb.toString()); Character y = 'c'; Character[] y1 = { 'd', 'e' }; if (y.getClass().isArray()) { for (int i = 0; i < y1.length; i++) { test = test.replaceAll(x[i].toString(), y1[i].toString()); } } else { test = test.replaceAll(sb.toString(), String.valueOf(y.toString())); } System.out.println(test); }
有一种更快的方式:
public static void main(String[] args) { String target = "ab"; String replacement = "**"; char[] array = "abcde".toCharArray(); for (int i = 0; i < array.length; i++) { int index = target.indexOf(array[i]); if (index != -1) { array[i] = replacement.charAt(index); } } System.out.println(array); }