Reputation: 75147
I have a regex as like that:
/^[0-9]*.*K/
and I have a string to test:
L1/50K
and it matches. However it should match a string starts with a number? What is the explanation of that regex?
Upvotes: 0
Views: 44
Reputation: 174716
Remove the *
after [0-9]
. *
repeats the previous (token or character) zero or more times, so if no number is present at the first, ^[0-9]*.*K
would match the string.
^\d\d*.*K$
OR
^\d+.*K$
OR
^\d{1,}.*K$
Use \d
at the first so that it would match the strings which starts with a digit. Note \d
is equal to [0-9]
. $
means end of the line, use this anchor after K
, so that it would match the lines which starts with a number and ends with a K
Upvotes: 0
Reputation: 145
a * matches 0 or more of the preceding token. if you want to force it to start with a number you should use a +, like:
/^[0-9]+.*K/
for excellent documentation on regexes, as well as build them: http://www.regexr.com/
Upvotes: 0
Reputation: 2397
'*' means 0 or more. You have to use +, which means 1 or more
/^[0-9]+.*K/
Upvotes: 1