SeaBass
SeaBass

Reputation: 1764

Check if a string starts with one letter followed by digit(s) and then any characters

How can I make the pattern below return true in scenarios like these:

m1, m1a, M100bc, s45, S396xyz

and false in scenarios like these:

'', m, 1, 1a, mm, Mx, mm1, SS1b

Pattern to tweak: /^m\S\.*/i.test(text)

Right now it takes any number of letters at the start and non-digits right after the first letter

Upvotes: 5

Views: 6813

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

You may use

/^[a-z]\d.*/i

See the regex demo. If the string can have line breaks, replace .* with [\s\S]*.

Details

  • ^ - start of string
  • [a-z] - an ASCII letter
  • \d - a digit
  • .* - any 0+ chars other than line break chars ([\s\S] will match any chars).

NOTE: The .* (or [\s\S]*) at the end are only a good idea if you need to use the match values. If not, when used with RegExp#test(), you may omit that part of the pattern.

Upvotes: 6

Nina Scholz
Nina Scholz

Reputation: 386520

You could just test the first two characters only.

var cases = ['m1', 'm1a', 'M100bc', 's45', 'S396xyz', '', 'm', '1', '1a', 'mm', 'Mx', 'mm1', 'SS1'];
console.log(cases.map(s => (/^[a-z]\d/i.test(s))));

Upvotes: 4

Related Questions