Reputation: 197
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:
match
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
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:
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
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