I want to use string in Java Replaceall (regex, regex) instead of (regex, string)

Example:

input = "10N10N";
input = input.replaceAll("1|N","N|1"); // Syntax not correct

Expected output: n01n01

What I want to ask is that the single line iterator replaces all "1" with "n" and all "n" with "1"

Solution

Because the Java 9 matcher class contains replaceall (function < matchresult, string > replacer), you can dynamically specify what should be used as a replacement according to the current matching So your code might look like this:

Map<String,String> replacementsMap = Map.ofEntries(
        Map.entry("1","N"),Map.entry("N","1")
);

String input = "10N10N";
Pattern p = Pattern.compile("1|N");
Matcher m = p.matcher(input);
String replaced = m.replaceAll(match -> replacementsMap.get(match.group()));
System.out.println(replaced);

Output: n01n01

Before Java 9, you could use matcher #appendreplacement and matcher #appendtail instead of replaceall

//create Pattern p,Matcher m and replacement map
StringBuffer sb = new StringBuffer();
while(m.find()){
    m.appendReplacement(sb,replacementsMap.get(m.group()));
}
m.appendTail(sb);
String replaced = sb.toString();

If you prefer to use external libraries, Apache Commons – Lang contains a stringutils class with replaceeach (string text, string [] searchlist, string [] replacementlist) methods You can use it as follows:

String input = "10N10N";
String replaced = StringUtils.replaceEach(input,new String[] {"1","N"},new String[] {"N","1"});
System.out.println(replaced);//N01N01
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>