Don't worry, I'm not asking you to help me find a regex!
I'm currently using the method
String.replaceAll(String regex, String replacement)
to parse a line of user-provided data and grab the username. I'm doing this by stripping the line of everything but the data I need, then returning that data.
Let's pretend
String rawTextInput = "Machine# 000111
Password: omg333444"
I want the username to be the Machine number. My method:
private String getUsername(String rawTextInput) {
String username = rawTextInput.replaceAll("(.+#\\s\\d{6,6})", "(\\d{6,6})");
return username;
}
The first argument, regex (.+#\s\d{6,6}) correctly identifies the first line of the raw input, Machine# 000111.
The second argument/regular expression (\d{6,6}) correctly isolates the data I want, 000111.
Basically, what this method is telling the program to do is "Find the line with Machine# 000111 and strip that line to 000111.
Actual output
However, I am obviously using the second argument of ReplaceAll() incorrectly, because I'm getting back the literal regular expression
username = "(\\d{6,6})"
Expected output
instead of
username = "omg333444"
What is the correct way to grab the username here? Is there a way to mimic the presence of a regex in the Replacement argument of ReplaceAll()?
Please note, the code blocks in this example have duplicate "\" characters because they are escape characters in IntelliJ IDEA.