51

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?

Tushar
  • 85,780
  • 21
  • 159
  • 179
Moritz Büttner
  • 794
  • 1
  • 8
  • 20

4 Answers4

75

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.

Tushar
  • 85,780
  • 21
  • 159
  • 179
30

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}$ 
Jerome WAGNER
  • 21,986
  • 8
  • 62
  • 77
5

you can use this code in regex

^\d{4}$
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
sinasho
  • 180
  • 2
  • 6
0

If you want to get into regex and match 4 numbers... You can backslash the periods too.

get-childitem | where name -match 'journal.\d{4}.txt'
js2010
  • 23,033
  • 6
  • 64
  • 66