-3

I am trying to write a regex pattern check to check if my string starts with numbers and ends with only '-' and one alphabet. Same of the regex that should pass is 1234-M

How d i write this? I wrote this but it allows for multiple alphabets at the end and doesnt add '-'.

"^\d*(?:_?[A-Za-z]{1,1})*$"

Any help is appreciated

Kingsley Simon
  • 1,796
  • 3
  • 27
  • 65
  • 1
    Please post the whole relevant code. Do you want to validate a string? Is it live input validation? Re-formatting a string? You say you want to match `-`, why do you have `_` in the pattern? `*` matches 0 or more occurrences, so `(?:_?[A-Za-z])*` matches `ASGHFdfgthh` strings. If you want to require 1 `_` and 1 letter, use `(?:_[a-zA-Z])?` instead of `(?:_?[A-Za-z]{1,1})*`. Same quantifier issue might be with `\d*`, you probably want `\d+`. And since it is a string literal, you should double the backslashes, or use a regex literal: `/^\d+(?:_[A-Za-z])?$/` – Wiktor Stribiżew Jun 26 '18 at 07:32
  • 1
    Did you try `^\d+-[a-zA-Z]$` ? – Bohemian Jun 26 '18 at 07:35
  • @Bohemian yes and doesnt work – Kingsley Simon Jun 26 '18 at 07:51
  • If you explained what you are doing, you would get better help, and faster. – Wiktor Stribiżew Jun 26 '18 at 08:01
  • @kingsley if it doesn’t work, why did you accept an answer with the same regex, and *how* doesn’t it work? – Bohemian Jun 26 '18 at 08:23
  • @Bohemian sorry i made a mistake earlier and then when it worked i accepted an answer – Kingsley Simon Jun 28 '18 at 07:49

1 Answers1

3

Maybe this is what you mean?

^\d+-[A-Za-z]$

The main corrections are:

  • you always want at least one number at the start, so use \d+ instead of \d*. The latter can match 0 numbers.
  • You wrote an underscore instead of a hyphen, typo?
  • {1,1} is unnecessary
  • * at the end there means that there can be 0 or more letters at the end. You only want one letter, so you should remove that.
  • Because of this, the non-capturing group is unnecessary.

Demo

Sweeper
  • 145,870
  • 17
  • 129
  • 225
  • @KingsleySimon can you describe how it does not work? What strings should match but doesn’t? What strings Matches but shouldn’t? – Sweeper Jun 26 '18 at 08:02