How to match only some characters with regular expression?

I want to check if a string matches only some regular expression characters.

For example, I would like to match only a , b or c .

So, "aaacb" will pass, but "aaauccb" will not (due to u ).

I tried this way:

 /[a|b|c]+/ 

but this will not work because an unsuccessful example passes.

+4
source share
3 answers

You need to make sure that your string consists of only these characters, binding the regular expression to the beginning and end of the string:

 /^[abc]+$/ 

You also mixed up two concepts. Alternation (which would be (a|b|c) ) and character classes (which would be [abc] ). In this case, they are equivalent. Your version also allows | as a symbol.

+8
source
  /[^abc]/ 

Is a copy example from rubular . It matches any single character except: a, b or c

0
source

Try [abc] +

It will match a, b or c.

-1
source

Source: https://habr.com/ru/post/1441840/


All Articles