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 :)
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With