There is one legitimate use case of .* though: advancing to the last match of something. If you want to find the last digit in a string, /.*(\d)/ will readily find it for you.
There is one legitimate use case of .* though: advancing to the last match of something. If you want to find the last digit in a string, /.*(\d)/ will readily find it for you.
$ anchors to the end of the string, \D clears the non-digits from the end to allow \d to match the digit '2'.
In this case when finding the last match from the end, would the lazy quantifier reduce backtracking? e.g. /(\d)\D*?$/
On the two options generally:
/(\d)\D*$/
is problematic if you have a lot of digits, while /.*(\d)/
is problematic if you have a lot of text after the last digit. Both could potentially be optimized by the engine to run right-to-left (the former because it's anchored to the end and the latter because it greedily matches to the beginning), and then both would do well. I'm not sure if that happens in practice.Overall, I prefer the latter, both because I think it's clearer and because its perf characteristics hold up under a wider variety of inputs.
Edit: how do you make literal asterisks on HN without having a space after them?
/.*(\d)/
- Searches right-to-left, backtracking until it finds the match. /(\d)\D*$/
- Searches left-to-right, going forward a step, backtrack, forward, backtrack, until it finds a match.If you're looking for a match toward the end of a string, the .* version will be faster.
If you have a complicated regex $r, you can only negate it with (?:(?!$r).), and in that case, .$r is much easier to read :-)
http://www.charbase.com/2169-unicode-roman-numeral-ten
(even more in http://www.charbase.com/block/number-forms)
I'm not sure if Javascript matches these in its \d pattern, however, but I think that most regexp engines default to the ascii [0-9] unless you are using \p{Number}.
false
There's a modifier if you want to only match ASCII digits.