Reputation: 10225
In my Ruby on Rails app I need a regex that accepts the following values:
{DD}
{MM}
{YY}
{NN}
{NNN}
{NNNN}
{NNNNN}
{NNNNNN}
-
, _
, .
and #
I am still new to regular expressions and I came up with this:
/\A[a-zA-Z._}{#-]*\z/
This works pretty well already, however it also matches strings that should not be allowed such as:
}FOO
or {YYY}
Can anybody help?
Upvotes: 1
Views: 42
Reputation: 627507
You may use
/\A(?:\{(?:DD|MM|YY|N{2,6})\}|[A-Za-z_.#-])*\z/
See Rubular demo
\A
- start of string anchor(?:\{(?:DD|MM|YY|N{2,6})\}|[A-Za-z_.#-])*
- a non-capturing group ((?:...)
that only groups sequences of atoms and does not create submatches/subcaptures) zero or more occurrences of:
\{(?:DD|MM|YY|N{2,6})\}
- a {
then either DD
, or MM
, YY
, 2 to 6N
followed with }
|
- or[A-Za-z_.#-]
- 1 char from the set (ASCII letter, _
, .
, #
or -
)\z
- end of string.Upvotes: 4