Reputation: 504
I want to validate some strings.
Rules: String can be contain A-Z, 0-9, "_", "!", ":".
If string contains 2x special characters, eg, "__" or "!!" or "K:KD:E" must return false.
Examples
Legitimate matches
FX:EURUSD
FX_IDC:XAGUSD
NYMEX_EOD:NG1!
Invalid matches:
0-BITSTAMP:BTCUSD - contains a minus sign)
2.5*AMEX:VXX+AMEX:SVXY - contains a *, a + and 2x ":"
AMEX:SPY/INDEX:VIX - contains a /
Upvotes: 1
Views: 80
Reputation: 504
I eventrually used pattern
var pattern = /^[a-zA-Z_!0-9]+:?[a-zA-Z_!0-9]+$/;
Upvotes: 0
Reputation: 4161
I would first start out with regex to remove all strings containing invalid characters:
/[^A-Z0-9_!:]/
I would then use this to check for duplicates:
/(_.*_)|(!.*!)|(:.*:)/
These can be combined to give:
/([^A-Z0-9_!:])|(_.*_)|(!.*!)|(:.*:)/
This can be seen in action here.
And here is a JSFiddle showing it working.
Upvotes: 0
Reputation: 786041
You can use this negative lookahead based regex:
/^(?:[A-Z0-9]|([_!:])(?!.*\1))+$/gm
([_!:])(?!.*\1)
will ensure there is no repetition of special characters.
Upvotes: 1