简体   繁体   中英

Java match regex then format string using second regex

I am attempting to first match a string with a regex pattern and then use a second pattern to format that string. From what i've read up on, one way of achieving this is using .replaceAll() ( edit : .replaceAll() is not used for this purpose, read comments on answer for clarification)

I have created this function whereby the aim is to:

  1. Match given string to match
  2. Format given string using format regex

     String match = "(^[AZ]{2}[0-9]{2}[AZ]{3}$)"; String format = "(^[AZ]{2}[0-9]{2}[*\\\\s\\\\\\\\][AZ]{3}$)"; String input = "YO11YOL" if (input.matches(match)) { return input.replaceAll(input, "??"); } 

The output should be YO11 YOL with a added space after the fourth character

This is what you want: Unfortunately it cannot be done the way that you want. But it can be done using substring .

public static void main(String args[]){
    String match = "(^[A-Z]{2}[0-9]{2}[A-Z]{3}$)";
    String input = "YO11YOL";

    if (input.matches(match)) {
       String out = input.substring(0, 4) + " " + input.substring(4, 7);
       System.out.println(out);
    }

}

You may use two capturing groups and refer to them from the string replacement pattern with placeholders $1 and $2 :

String result = input.replaceFirst("^([A-Z]{2}[0-9]{2})([A-Z]{3})$", "$1 $2");

See the regex demo and a diagram:

在此处输入图片说明

Note that .replaceFirst is enough (though you may also use .replaceAll ) as there is only one replacement operation expected (the regex matches the whole string due to the ^ and $ anchors ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM