ManreeRist
ManreeRist

Reputation: 504

javascript regex matching string conditions including special characters

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

Answers (3)

ManreeRist
ManreeRist

Reputation: 504

I eventrually used pattern

var pattern = /^[a-zA-Z_!0-9]+:?[a-zA-Z_!0-9]+$/;

Upvotes: 0

JosephGarrone
JosephGarrone

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

anubhava
anubhava

Reputation: 786041

You can use this negative lookahead based regex:

/^(?:[A-Z0-9]|([_!:])(?!.*\1))+$/gm

RegEx Demo

([_!:])(?!.*\1) will ensure there is no repetition of special characters.

Upvotes: 1

Related Questions