简体   繁体   中英

(Java) How to mimic a regex in the “replacement” argument of String.replaceAll()?

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.

IntellIJ actually does this for the replace option. You can test it out by hitting Ctrl+R (or the equivalent on your platform) and playing with it.

The answer is that groups are given a number based on their position while parsing. For example, your current Regex would be considered one group, because there is one set of parenthesis surrounding the entire match. If you isolate the numbers in its own separate group, you will be able to use that in the replacement. Your new regex might look something like this:

.+#\\s(\\d{6,6})

In that, the numbers are isolated in the first group.

Groups are then denoted by their location and a $ in front of it. So your new replace would look something like this:

String username = rawTextInput.replaceAll(".+#\\s(\\d{6,6})", "$1");

More information about the replacement character is on this thread .

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