I need to pass strings like:
/test/
Some illegal things would be:
\test\
\test
/test
I need to pass strings like:
/test/
Some illegal things would be:
\test\
\test
/test
Something like this should match your strings.
^/.*/$
So that regex expects a the string to start and end with a forward slash and can have anything in between.
If you want to allow only lower-case alphabetic characters between the slash characters, try this:
^\/[a-z]+\/$
Explanation:
^ require match to start at the very beginning of the string
\ escape the forward slash in the input string
[a-z] the character class representing the set of lower case characters
+ the preceding character or character class occurs one or more times
$ require match to end at the very end of the string
Edit: When I answered this question, I confess to probably not noticing the qregexp tag among the four tags originally on the question. Some regex parsers (such as that provided by Perl) require that a delimiter character be used to designate the start and end of a pattern. For such regex parsers, the forward slash /
is commonly used as a delimiter character. If that is the case, it is necessary to escape a /
that appears in the regex pattern.
A question has been raised if it is necessary to escape a /
that appears in a regex pattern to be processed by qregexp
. Perhaps not–I'll leave that to be answered by the qregexp
experts. That said, for regexp parsers that do not required a /
to be escaped, the escape character \
can be dropped from the pattern that I show above:
^/[a-z]+/$
Finally, if a particular regex might be used in more than one environment, it doesn't hurt to escape a character that might be deemed special in one of those environments.