1

In my Ruby on Rails app I need a regex that accepts the following values:

  • {DD}
  • {MM}
  • {YY}
  • {NN}
  • {NNN}
  • {NNNN}
  • {NNNNN}
  • {NNNNNN}
  • upper and lowercase letters
  • the special characters -, _, . 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?

Tintin81
  • 8,860
  • 17
  • 66
  • 143

1 Answers1

4

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.
Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397