Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA - replaceAll in a regex with $1

On a CodeFight problem it is asked to extract the first digits of a String and return it as a string, return null if it doesn't start with digits.

I used regex, no problem, yet I don't understand very well the top answer :

String longestDigitsPrefix(String inputString) {
    return inputString.replaceAll("^(\\d*).*","$1");
}

If somebody can explain that'd be awesome :)

like image 963
Bruno Avatar asked Apr 05 '17 00:04

Bruno


1 Answers

The regex ^(\\d*).* always matches the entire input, capturing (via the brackets) the leading (the ^ means "start of input") digits (if any - the * means 0 or more and \d means "a digit")

The replacement string $1 means "group 1" (the first group made by a set of brackets).


Actually, the solution given is not the most elegant. This is better/simpler/faster/more readable:

String longestDigitsPrefix(String inputString) {
    return inputString.replaceAll("\\D.*", "");
}

This regex matches from the first non-digit encountered to the end and just deletes it (replaces with nothing).

like image 78
Bohemian Avatar answered Nov 13 '22 01:11

Bohemian