Ok, i have a regex pattern like this /^([SW])\w+([0-9]{4})$/
This pattern should match a string like SW0001
with SW
-Prefix and 4 digits.
I thougth [0-9]{4}
would do the job, but it also matches strings with 5 digits and so on.
Any suggestions on how to get this to work to only match strings with SW
and 4 digits?
Add the $ anchor. /^SW\d{4}$/ . It's because of the \w+ where \w+ match one or more alphanumeric characters. \w+ matches digits as well.
match(/(\d{5})/g);
\d for single or multiple digit numbers It will match any single digit number from 0 to 9. \d means [0-9] or match any number from 0 to 9. Instead of writing 0123456789 the shorthand version is [0-9] where [] is used for character range. [1-9][0-9] will match double digit number from 10 to 99.
Most characters, including all letters ( a-z and A-Z ) and digits ( 0-9 ), match itself. For example, the regex x matches substring "x" ; z matches "z" ; and 9 matches "9" . Non-alphanumeric characters without special meaning in regex also matches itself. For example, = matches "=" ; @ matches "@" .
Let's see what the regex /^([SW])\w+([0-9]{4})$/
match
\w
= [a-zA-Z0-9_]
)This match more than just SW0001
.
Use the below regex.
/^SW\d{4}$/
This regex will match string that starts with SW
followed by exactly four digits.
in regex,
^
means you want to match the start of the string$
means you want to match the end of the stringso if you want to match "SW" + exactly 4 digits you need
^SW[0-9]{4}$
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