-5

My sample input is "0X10001,0X10002,0X610001,0X610002"

System.out.println(st.replaceAll(regex, "0"));

My output should be "010001,010002,610001,610002"
0X should be replaced by
0 --> if length is 7
""--> if length is 8

what is the regex I have to use?
([0X]){1,2} not getting desired output by this.

Til
  • 5,150
  • 13
  • 26
  • 34
Tej4493
  • 1
  • 2

2 Answers2

2

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.

Andreas
  • 154,647
  • 11
  • 152
  • 247
-2

replaceAll("0X(?=\\d{6})|(0)X(?=\\d{5})", "$1") works fine for the given issues

Raibaz
  • 9,280
  • 10
  • 44
  • 65
Tej4493
  • 1
  • 2