0

I need to validate the following string

case 1: 123E

The first three are numeric and then the alphabet.

I have created the following pattern

var pattern = @"^[0-9]{2}[a-zA-Z]{1}"

Is this correct?

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
tyu
  • 1
  • 5

2 Answers2

1

Something like that should work: ^[0-9]{3}[a-zA-Z]$ You put {2} for numbers but in your case there are 3 of them so I wrote {3} instead. You don't need to write {1} because [a-zA-Z] is enough to find exacly one letter. I also added endline tag $ to ensure that there are no more symbols after letter.

Sergio
  • 65
  • 1
  • 5
1

You were close, as per my comment you can use:

^\d{3}[a-zA-Z]$

See the online demo

  • ^ - Start string anchor.
  • \d{3} - Three digits where \d is shorthand for [0-9]1
  • [a-zA-Z] - A single alpha char.
  • $ - End string anchor.

See a working .Net example here

1: This would only be the case if the ECMAScript flag is enabled. Otherwise \d is matching non-ascii digits as per this link. Thanks @WiktorStribiżew for noticing.

JvdV
  • 70,606
  • 8
  • 39
  • 70
  • In .NET regex, when one wants to match ASCII digits, it [is safer](https://stackoverflow.com/questions/16621738/d-is-less-efficient-than-0-9) to use `[0-9]`. Your pattern [also matches](http://regexstorm.net/tester?p=%5e%5cd%7b3%7d%5ba-zA-Z%5d%24&i=%e0%b1%a6%e1%a7%97%e0%b5%adA) `string Case1 = "౦᧗൭A";`. So, "*`\d` is shorthand for `[0-9]`*" is not correct in .NET regex context. – Wiktor Stribiżew Jan 22 '21 at 09:20
  • @WiktorStribiżew, thanks for noticing. I added a disclaimer. – JvdV Jan 22 '21 at 09:33