5

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 :)

Bruno
  • 148
  • 2
  • 6
  • 1
    Are you sure it's supposed to return `null` if it doesn't start with digits? Because the method you've posted returns the empty string `""` in that case. – ruakh Apr 05 '17 at 00:55
  • Possible duplicate of [Reference - What does this regex mean?](http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) – Tom Apr 05 '17 at 14:37

1 Answers1

7

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).

Bohemian
  • 365,064
  • 84
  • 522
  • 658
  • 1
    Yes the function is supposed to return null. Thanks a lot Bohemian, actually what confused me is that I thought ^(\\d*) was the same as \\D* ! Your solution is even better ! I'm quite amazed by regex in general and how efficient it can be, but it's not super easy to master. – Bruno Apr 05 '17 at 14:29