Do it like this:
String st = "0X10001,0X10002,0X610001,0X610002";
System.out.println(st.replaceAll("0X(?=\\d{6})|(0)X(?=\\d{5})", "$1"));
Output
010001,010002,610001,610002
Explanation
As the regex engine scans, the pattern |
will always try left side before right side, so as it advances, it will first it try 0X(?=\\d{6})
, which is a match for 0X
followed by 6 digits (using zero-width positive look-ahead). If that matches, nothing is captured, so $1
is empty, and 0X
is replaced by empty string.
If that didn't match, it tries (0)X(?=\\d{5})
, i.e. match 0X
followed by 5 digits. If that matches, the 0
is captured in group 1, so $1
is 0
, and 0X
is replaced by 0
.
If neither match, the regex engine will try again at the next position in the input string.