简体   繁体   中英

Starts With Character Does Not Match at Regex

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?

'*' means 0 or more. You have to use +, which means 1 or more

/^[0-9]+.*K/

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM