user1353436
user1353436

Reputation: 31

Regular expression for lower case and not starts with fixed letter

I am at my wits end to make it work.
All I need is to :
1. Input should not start with LOVE.
2. Not all valid characters must be same.
3. There must be at least 6 valid characters (Upper case and numeric) with maximum of 18.
4. Other allowed characters are space, ampersand (&), hyphen, full stop, solidus (/).

Examples :
ERTYUII is allowed
afgTYULO is not allowed (contains only 5 valid chars)
LOVE12345WERT is not allowed (starts with LOVE).
asdERTY12^& is allowed (at least 6 valid characters (ERTY12 upper and numeric))
asAAertArtytyAtytytuArtyttyAyuyuyyA not allowed even though we have 6 valid chars but they are all same.

Please advice.

Note : I edited this question because I forgot to miss some points in my assignment :(.

Upvotes: 0

Views: 3988

Answers (1)

user1919238
user1919238

Reputation:

Note: this regex matched the description given in the original question. The edits have since changed the requirements substantially.

This regex should work, if I understand you correctly:

/^(?!LOVE)[^a-z]+$/

This will match anything that does not start with LOVE and contains no lowercase letters.

(note: this assumes a standard English alphabet, a-z only)

Explanation:

^ and $ anchor to the beginning and end of the string. This forces the pattern to match the entire string.

(?!LOVE) is a look-ahead. It checks that the string does not start with LOVE, but it doesn't move the match position forward at all. Thus the rest of the regex still checks against the entire string.

[^a-z] a negated character class, matching anything that is not a lowercase letter.

+ matches the previous thing one or more times. So it matches one or more characters that are not a lowercase letter.

Update:

So you also want to disallow anything that is only the same character repeated? Here is a regex that matches a string that only contains the same character:

/^(.)\1+$/

(.) matches a single character and puts it in the first capturing group.

\1+ matches one or more occurrences of the capturing group.

In this case, because it matches the input you don't want, you would have to check that the regex doesn't match.

It is possible to combine this in the same regex using another look-ahead:

 /^(?!LOVE)(?!^(.)\1+$)[^a-z]+$/

However, as you add more and more conditions to the same regex, it becomes harder and harder to understand. If you have to make several checks, it is often wiser to separate them into different regexes.

Upvotes: 3

Related Questions