Sha-1
Sha-1

Reputation: 197

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 = "(^[A-Z]{2}[0-9]{2}[A-Z]{3}$)";
    String format = "(^[A-Z]{2}[0-9]{2}[*\\s\\\\][A-Z]{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

Upvotes: 0

Views: 156

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626691

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:

enter image description here

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).

Upvotes: 0

Dylan
Dylan

Reputation: 1395

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);
    }

}

Upvotes: 3

Related Questions