Ronald Wildenberg
Ronald Wildenberg

Reputation: 32134

Regular expression for a string with a max length that contains a required part?

I'm not exactly a regex guru, so I have some difficulty finding a regular expression for the following case.

I'd like to match a string of the form <prefix>$rolename$<suffix> (e.g. abc$rolename$def) that has a maximum length of 20. Both <prefix> and <suffix> can be empty and may contain any character. The $rolename$ part is required.

Shouldn't be difficult but I just can't figure out how to do this. Can anyone help me?

Upvotes: 4

Views: 7551

Answers (3)

Kobi
Kobi

Reputation: 138137

Since you have to use a regex, as you've explained, here's an option:

^(?!.{21,})(.*?)\$rolename\$(.*?)$

This is similar to Joachim's answer, but with a negative lookahead at the beginning. That is: before the regex is matched, we check the string does not have 21 or more characters.

Upvotes: 6

ghostdog74
ghostdog74

Reputation: 343077

why regex? think simple. depending on your language, check for length using your language's string length methods eg using Python

if len(mystring) <= 20:
     if "$rolename" in mystring:
         print "ok"

your language may have similar methods like index() to find where a substring is in a string.

Upvotes: -1

Joaquim Rendeiro
Joaquim Rendeiro

Reputation: 1388

The regular expression I'd use would be /^([^\$]*)\$rolename\$([^\$]*)$/, validating the total length of the string externally.

Upvotes: 1

Related Questions