user532339
user532339

Reputation: 189

Optional Characters, Numbers, Symbols regex

The regex task that I am trying to achieve is pretty simple. A string can contain one of the following:

I have been able to achieve the first two points but I am struggling to get the last one.

/^(?=.*[a-z])(?=.*[0-9]).{7,}$/

Strings that should match are as followed:

Please note that for the last scenario when I say alphabet plus symbols. I'd like it to match any symbols. I did alternatively try:

/(.*).{7}/

And this did not work. Reason being because that means an individual could enter just letters. So in order for the regex to satisfy it needs to be one of the following above as stated.

Upvotes: 1

Views: 110

Answers (2)

Bohemian
Bohemian

Reputation: 425033

I sense that by "plus" you mean "then", so this should do it:

^(?=.{7,})[a-zA-Z]+(?!$)[0-9]*[^a-zA-Z0-9]*$

This regex requires that if numbers and symbols are present, that number precede symbols.

Here "symbol" is defined as any character not a letter or number, you may want to instead list the characters that are "symbols", eg [@%#()*]

A negative look ahead is used to require that at least some characters must follow the letters.

Upvotes: 2

d'alar'cop
d'alar'cop

Reputation: 2365

Depending on my interpretation, this might work:

/^[a-zA-Z]+[^a-zA-Z]+$/

Upvotes: 3

Related Questions