[英]javascript regex matching string conditions including special characters
I want to validate some strings. 我想验证一些字符串。
Rules: String can be contain AZ, 0-9, "_", "!", ":". 规则:字符串可以包含AZ,0-9,“ _”,“!”,“:”。
If string contains 2x special characters, eg, "__" or "!!" 如果字符串包含2个特殊字符,例如“ __”或“ !!” or "K:KD:E" must return false.
或“ K:KD:E”必须返回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 /
You can use this negative lookahead based regex: 您可以使用以下基于负前瞻的正则表达式:
/^(?:[A-Z0-9]|([_!:])(?!.*\1))+$/gm
([_!:])(?!.*\\1)
will ensure there is no repetition of special characters. ([_!:])(?!.*\\1)
将确保不重复特殊字符。
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. 这是一个JSFiddle显示它的工作原理。
我最终使用了模式
var pattern = /^[a-zA-Z_!0-9]+:?[a-zA-Z_!0-9]+$/;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.