theJuls
theJuls

Reputation: 7470

Match a single Regex character that is within a certain range

Seems quite simple, but I can't find how to do this. I want to match a single character within a certain range, say a to z.

[a-z]

Currently doing the following:

const regex = RegExp('[a-z]');
console.warn('TEST', regex.test('a'))

Simple enough. However I want it to be a single character. If there is any more than one, regardless if they also belong in that range, it needs to fail. So for example:

You get the idea.

I have tried some variations such asL

[{1}a-z]

Which doesn't do anything. Ultimately it still accepts any combination of character within that range.

Upvotes: 1

Views: 205

Answers (1)

user47589
user47589

Reputation:

Pin the string down using ^ and $, which match the "start of string" and the "end of string", respectively.

Your regex would be ^[a-z]$, which means you expect to match a single character between a and z, and that single character must be the entire string to match.

The reason [a-z]{1} (which is equivalent to [a-z]) doesn't work is because you can match single characters all along the string. The start/end of the string aren't "pinned down".

let str = ['a','b','ab','aa','abcdefg'];
const regex = /^[a-z]$/;
str.forEach(w => console.warn(w, regex.test(w)));

By the way, [{1}a-z] doesn't do what you think it does. You intended to match a single alphabetic character, but this adds three more characters to the match list, which becomes:

  • a-z
  • {
  • }
  • 1.

I think you meant [a-z]{1}, which as previously noted is equivalent to [a-z].

Upvotes: 6

Related Questions