michele
michele

Reputation: 26598

Java regex for replaceAll

What is the regex expression for replace all the A char with A1, B->B1, C->C1, D->D1 and E->E1 string?

//AND(A<>B,C>D)?GREEN(E-E)

String expr ="AND(A<>B,C>D)?GREEN(E-E)";
String regex="";
expr.replaceAll(regex, "N1");
System.out.println(expr);

The result may be:

AND(A1<>B1,C1>D1)?GREEN(E1-E1)

Thank you

Upvotes: 0

Views: 846

Answers (1)

Federico Piazza
Federico Piazza

Reputation: 31035

You can use a regex like this:

\b([A-E])\b

With the replacement string $11

Bear in mind that in java you have to escape backslasher, so you have to use:

String expr = "AND(A<>B,C>D)?GREEN(E-E)";
expr = expr.replaceAll("\\b([A-E])\\b", "$11");
System.out.println(expr);

Java demo

Regex demo

enter image description here

Update: following your comment, if you want to extend the regex to all letters, then replace [A-E] to [A-Z].

Upvotes: 1

Related Questions