Home > Blockchain >  Regex Split and Replace string - Java
Regex Split and Replace string - Java

Time:04-30

I am trying to match a regex pattern to replace a particular string.

Sample Text : ABC/1111111031111111/0318*12345678

\/(\d{12,19})\/(0[1-9]|1[0-2])(\d{2})\*

I want to replace the 03 and 18 in /0318 with with "/1222" i.e (Dec-2022). I tried the string replaceAll method but that replaces all the matched characters in the provided sample string. Something like below;

Sample Code i tried:

sampleText.replace(matcher.group(2), "12");

sampleText.replace(matcher.group(3), "22")

How can i do this ?

SAMPLE I/P EXPECTED O/P
ABC/1111111031111111/0318*12345678 ABC/1111111031111111/1222*12345678
ABC/1852111031156311/1120*12345678 ABC/1852111031156311/1222*12345678

CodePudding user response:

That is because you are replacing the match from group 2 (which is 03) with 12, and replacing the match from group 3 (which is 18) with 22 using String replace() which replaces all occurrences.

Java supports a finite quantifier in a lookbehind assertion using a regex, and you can get a match only to replace with the string 1222 (you don't need 2 separate groups to match the 4 digits).

(?<=/\d{12,19}/)(?:0[1-9]|1[0-2])\d{2}(?=\*)

Explanation

  • (?<=/\d{12,19}/) Assert 12-19 digits between / to the left
  • (?:0[1-9]|1[0-2])\d{2} Match 01 - 09 or 1-2 followed by 2 digits
  • (?=\*) Assert * to the right

See a Java and a regex demo.

Example

String sampleText = "ABC/1111111031111111/0318*12345678\n"
          "ABC/1852111031156311/1120*12345678";

String pattern = "(?<=/\\d{12,19}/)(?:0[1-9]|1[0-2])\\d{2}(?=\\*)";

System.out.println(sampleText.replaceAll(pattern, "1222"));

Output

ABC/1111111031111111/1222*12345678
ABC/1852111031156311/1222*12345678

CodePudding user response:

You can use

(/\d{12,19}/)(?:0[1-9]|1[0-2])\d{2}(\*)

Replace with $11222$2. See the regex demo.

Details:

  • (/\d{12,19}/) - Group 1: /, 12 to 19 digits
  • (?:0[1-9]|1[0-2]) - 0 and then a non-zero digit, or a 1 and then 0, 1 or 2
  • \d{2} - two digits
  • (\*) - Group 2 ($2): a * char.

See the Java demo

List<String> strs = Arrays.asList(
        "ABC/1111111031111111/0318*12345678", 
        "ABC/1111111031111111/1120*12345678");

String pattern = "(/\\d{12,19}/)(?:0[1-9]|1[0-2])\\d{2}(\\*)";
for (String str : strs)
    System.out.println(str   " => "   str.replaceAll(pattern, "$11222$2"));

Output:

ABC/1111111031111111/0318*12345678 => ABC/1111111031111111/1222*12345678
ABC/1111111031111111/1120*12345678 => ABC/1111111031111111/1222*12345678
  • Related