Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx match exactly 4 digits

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?

like image 436
Moritz Büttner Avatar asked Mar 08 '17 14:03

Moritz Büttner


People also ask

How does regex match 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.

How does regex Match 5 digits?

match(/(\d{5})/g);

How do you find digits in regex?

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

How do I match a pattern in regex?

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 "@" .


2 Answers

Let's see what the regex /^([SW])\w+([0-9]{4})$/ match

  1. Start with S or W since character class is used
  2. One or more alphanumeric character or underscore(\w = [a-zA-Z0-9_])
  3. Four digits

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.

like image 65
Tushar Avatar answered Oct 14 '22 23:10

Tushar


in regex,

  • ^ means you want to match the start of the string
  • $ means you want to match the end of the string

so if you want to match "SW" + exactly 4 digits you need

^SW[0-9]{4}$  
like image 43
Jerome WAGNER Avatar answered Oct 14 '22 22:10

Jerome WAGNER