简体   繁体   中英

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.

[az]

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:

  • a should pass
  • b should pass
  • ab should fail
  • aa should fail
  • abcdefg should fail

You get the idea.

I have tried some variations such asL

[{1}az]

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

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

Your regex would be ^[az]$ , 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 [az]{1} (which is equivalent to [az] ) 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 = /^[az]$/; str.forEach(w => console.warn(w, regex.test(w))); 

By the way, [{1}az] 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:

  • az
  • {
  • }
  • 1 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM