Regex grouping: must start with /, optional group of characters alpha-numeric with forward slashes and total 1-255 characters

Viewed 89

I have an HTML5 input element with a pattern attribute. I'm having some trouble with an optional group.

  • The (relative) URL must start with a forward slash (I have this working).
  • The total (relative) URL may contain a total of up to 255 characters.
  • All characters from 2-255 must be (lowercase) alpha-numeric or a forward slash.

Separately the forward slash regex works and the 2-255 part works for alpha-numeric and forward slashes. However I'm having trouble allowing both groups with the second group being optional.

What I have confirmed to work:

pattern="^\/"
pattern="[a-z0-9\/]"

However I can't determine how to allow the second group as an option (I've tried adding the ? after the ending square bracket in example without luck).

I also am not sure how to combine the length ({255,}) bit to the total pattern expression.

How do I combine all three aspects of the regular expression?

Note: tags seem to be broken at the moment of posting this.

1 Answers

You can use

pattern="/[a-z0-9/]{0,254}"

You do not need ^ nor $ in the pattern regex, by the way, it must match the whole string anyway, it will be parsed as ^(?:/[a-z0-9/]{0,254})$ pattern. That is, it will match a string that starts with / and then contains 0 to 254 lowercase ASCII letters, digits or slashes till the string end.

Note that / should only be escaped in regex literals where / is used as a delimiter char. pattern regexps are defined with literal strings.

Related