-3

I try make regular expression for one letter Z and 12 digits.

event.target.value = event.target.value.replace(/[^Z{1}+(\d{12})]/, '');

It is necessary for me that in the input field it was possible to enter one letter Z and then 12 digits only.

Please help me.

Vlad
  • 91
  • 5
  • Why do you have `[]` in the regexp? `[]` is used for matching a character in a set, not for grouping. – Barmar Jan 22 '23 at 19:32
  • I'm new to regular expressions... can you suggest your solution? For example, I have a solution for entering only numbers and it works. How can you do the same solution, but to enter one letter Z and then 12 digits? event.target.value = event.target.value.replace(/[^\d.]*/g, ''); – Vlad Jan 22 '23 at 19:35

1 Answers1

0

The regexp is

/^Z\d{12}$/
  • ^ matches the beginning of the string
  • Z matches the initial Z. There's no need for {1} since patterns always match exactly one time unless quantified.
  • \d{12} matches exactly 12 digits
  • $ matches the end of the string

const regex = /^Z\d{12}$/;

console.log(regex.test('Z123456789012')); // true
console.log(regex.test('X123456789012')); // false - begins with wrong letter
console.log(regex.test('Z1234567890')); // false - <12 digits
console.log(regex.test('Z123456A89012')); // false - letter mixed into digits
console.log(regex.test('Z123456789012345')); // false - >12 digits
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • This solution allows you to enter any letters and numbers in the input field... – Vlad Jan 22 '23 at 19:39
  • No it doesn't. `Z` only matches `Z`. – Barmar Jan 22 '23 at 19:40
  • I've added a code snippet showing that it doesn't match other things. – Barmar Jan 22 '23 at 19:42
  • 1
    event.target.value = event.target.value.replace(/^Z\d{12}$/, ''); - any letters... – Vlad Jan 22 '23 at 19:43
  • 1
    Why are you using replace? If the input doesn't match, there's nothing to replace, so it stays the same. – Barmar Jan 22 '23 at 19:44
  • I use field replacement when only numbers need to be entered and it works. But I need this replace for Z + 12 digits – Vlad Jan 22 '23 at 19:46
  • `if (!event.target.value.match(/.../)) { event.target.value = ''; }` – Barmar Jan 22 '23 at 19:47
  • For example, this code allows you to enter only the letter Z and numbers in the field. event.target.value = event.target.value.replace(/[^Z0-9]*/g, ''); But I need to be able to enter the letters Z and 12 numbers. How to do it? – Vlad Jan 22 '23 at 19:51
  • 1
    Remember that `replace()` REMOVES the match. So the pattern has to match what you DON'T want, not what you want to ALLOW. – Barmar Jan 22 '23 at 19:54
  • This solution id working - ` event.target.value = event.target.value.replace(/^[^Z\d]*(([Z]\d{0,12})?).*$/g, '$1');` – Vlad Jan 22 '23 at 20:35
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/251327/discussion-between-vlad-and-barmar). – Vlad Jan 22 '23 at 20:37