Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex in JavaScript - Match a string like "ABC12" [closed]

How to match the following string using regular expression in JavaScript?

  1. Has a total of 5 characters
  2. First 3 charaters are capital letters
  3. Last 2 characters are only numbers

I have got this pattern, [A-Z]{3}[0-9]{2}, but seems that it's still missing something.

like image 387
woodykiddy Avatar asked Oct 17 '12 08:10

woodykiddy


People also ask

How do you check if a regex matches a string?

Use the test() method to check if a regular expression matches an entire string, e.g. /^hello$/. test(str) . The caret ^ and dollar sign $ match the beginning and end of the string. The test method returns true if the regex matches the entire string, and false otherwise.

What does regex (? S match?

3.6. (? i) makes the regex case insensitive. (? s) for "single line mode" makes the dot match all characters, including line breaks.

What does G mean in regex?

g is for global search. Meaning it'll match all occurrences. You'll usually also see i which means ignore case. Reference: global - JavaScript | MDN. The "g" flag indicates that the regular expression should be tested against all possible matches in a string.

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


1 Answers

You also need anchors:

var regexp = /^[A-Z]{3}[0-9]{2}$/

Otherwise, substrings will also match (like ABC12 within xyzABC1234).

  • ^ means "start of string"
  • $ means "end of string"
like image 161
Tim Pietzcker Avatar answered Oct 25 '22 03:10

Tim Pietzcker