0

I have multiple line string below

A00233400193445 123394001

A83485800193471 982001134

I would like to replace 001 in the first column to 002

A00233400293445 123394001

A83485800293471 982001134

I have try ^A[0-9]{6}(001) with string.replaceAll(matcher.group(1), "002") but it replace all 001 to 002

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Ken
  • 11
  • Does this answer your question? [How to replace all occurrences of a string?](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string) – K. Martin Nov 26 '20 at 17:02
  • @K.Smith Probably not since based on example OP doesn't really want to replace *all* occurrences of specified string but only those in first column. – Pshemo Nov 26 '20 at 17:05
  • @K.Smith That question is a **JavaScript** question, not a **Java** question, so it cannot be the duplicate of this question. – Mark Rotteveel Nov 26 '20 at 17:24
  • The duplicate explains the basics, but also look at the documentation of [`Matcher`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/regex/Matcher.html). – Mark Rotteveel Nov 26 '20 at 17:27
  • Actually, the dupe is https://stackoverflow.com/questions/988655/can-i-replace-groups-in-java-regex. See [this answer](https://stackoverflow.com/a/49024941/3832970). – Wiktor Stribiżew Nov 26 '20 at 18:04

2 Answers2

2

Based on "I have multiple line string" I am assuming you have one string which contains data like:

String data = "A00233400193445 123394001\n" +
              "A83485800193471 982001134";

In such case your pattern ^A[0-9]{6}(001) is quite close to final solution, but you will need

  • to use MULTILINE flag which lets ^ and $ to match not only start and end of entire text, but start and end of each line. That flag can be enabled by (?m) syntax which starts section for regex where flag should be applied.
  • to store somewhere match of A[0-9]{6} part, which can be done by capturing-group, like you did for (001) part (probably unnecessarily here since you don't really want to reuse that match anywhere).

So your final solution can look like

String data =
        "A00233400193445 123394001\n" +
        "A83485800193471 982001134";

data = data.replaceAll("(?m)(A[0-9]{6})001","$1002"); //$1 represents match of group 1 (A[0-9]{6})

System.out.println(data);

Output:

A00233400293445 123394001
A83485800293471 982001134
Pshemo
  • 122,468
  • 25
  • 185
  • 269
1

You could use string.replaceAll passing the regex as a string and use multiline using an inline modifier (?m)

(?m)^(A[0-9]{6})001
     |         |
     | group 1 |

In the replacemen use group 1 followed by 002 $1002

final String regex = "(?m)^(A[0-9]{6})001";
final String string = "A00233400193445 123394001\n\n"
 + "A83485800193471 982001134";


System.out.println(string.replaceAll(regex, "$1002"));

Output

A00233400293445 123394001

A83485800293471 982001134

Java demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70