0

Here is the text

<some string here could contain W or L letter><W1>123<W2>123<W3>123. 

I hope to replace

<W(number)> 

pattern to

<L(number)>

pattern.

String str = "<WLWLWL><W1><FS>123<W2><FS>345<E>";
    System.out.println(str);

    Pattern p = Pattern.compile("<[A-Z]\\d>");
    Matcher m = p.matcher(str);

    while(m.find()){
        System.out.println(m.group());
    }

    str.replaceAll("<[A-Z]\\d>", "<L\\d>");
    System.out.println(str);

I can find exactly what I want with code above but the replace is not working.

I suppose the replace string doesn't take the regex in it. So what's the best way to do it?

shmosel
  • 49,289
  • 6
  • 73
  • 138
apolloneo
  • 169
  • 1
  • 2
  • 18
  • 1
    What is not working with your replace? Does it throw an error? (If yes, please [edit] the question and add the stacktrace.) Does it produce some unexpected result? (If yes, please [edit] the question and add your expected and actual output). It it something else? [edit] the question and don't make me guess what is wrong. – Johannes Kuhn Sep 03 '19 at 22:49

2 Answers2

3

I think you're looking for a capturing group:

str = str.replaceAll("<[A-Z](\\d)>", "<L$1>");

Note the assignment at the beginning. replaceAll() doesn't modify the string (strings are immutable); it returns a new one.

shmosel
  • 49,289
  • 6
  • 73
  • 138
1

Another alternative you can try is to use regex look around.

str = str.replaceAll("[a-zA-Z](?=\\d)", "L");

RegEx explanation:

[a-zA-Z](?=\\d)    finds the letter within (a-zA-Z) which has a number after it

Output:

<WLWLWL><L1><FS>123<L2><FS>345<E>

Source: Regex lookahead, lookbehind and atomic groups

More on RegEx Pattern: Class Pattern

replaceAll():

Also replaceAll() does modify the String you pass as parameter but instead the function return a new one since Strings are immutable. From String Java:

public String replaceAll(String regex, String replacement)
Returns:
   The resulting String
Yoshikage Kira
  • 1,070
  • 1
  • 12
  • 20