4

I want to check if a string matches only some characters with a regex.

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

So, "aaacb" would pass, but "aaauccb" would not (because of the u).

I have tried this way:

/[a|b|c]+/

but it does not work, because the failing example passes.

David Morales
  • 17,816
  • 12
  • 77
  • 105

3 Answers3

8

You need to make sure that your string consists only of those characters by anchoring the regex 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]). They are in this case equivalent. Your version would also allow | as a character.

Martin Ender
  • 43,427
  • 11
  • 90
  • 130
0
 /[^abc]/

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

steenslag
  • 79,051
  • 16
  • 138
  • 171
  • Yup that makes things a bit simpler. But note that the result needs to be inverted for the required check, and the check for non-empty strings has to be done separately now. – Martin Ender Oct 24 '12 at 15:14
  • This differs from the stated behavior in the empty string edge case. – Deestan Oct 24 '12 at 15:16
-1

Try [abc]+

It will match a, b or c.

Pal R
  • 534
  • 4
  • 11