简体   繁体   English

Javascript正则表达式仅验证“用逗号分隔的句子”

[英]Javascript Regex to Validate only “sentence separated by comma”

I need to validate this string in javascript. 我需要在javascript中验证此字符串。

the availability on the second argument is restricted to R1, R2, R3, R4 the second and third argument can only be separated by comma, while the first and the second is by space. 第二个参数的可用性仅限于R1,R2,R3,R4,第二个和第三个参数只能用逗号分隔,而第一个和第二个参数则由空格分隔。

req R1,1 //valid
req R2,3 //valid
req R0,1 //invalid
req R1 1 //invalid

I have written this: 我写了这个:

/^req\sR1|R2|R3|R4[^,][0-9]+$/

but it fails on few cases: 但在某些情况下失败:

req R3 1 //supposed to be invalid, valid using above regex
req R3.1 //supposed to be invalid, valid using above regex

Remove the negated character class and this R1|R2|R3|R4 . 删除否定的字符类和该R1|R2|R3|R4 R1|R2|R3|R4 won't do the thing you need. R1|R2|R3|R4不会做您需要的事情。 You need to put this into non-capturing group or capturing group to make it to work . 您需要将其放入非捕获组或捕获组以使其起作用。 Like this ^req (?:R1|R2|R3|R4),\\d+$ You could shorten this regex like the below 像这样的^req (?:R1|R2|R3|R4),\\d+$您可以像下面这样缩短此正则表达式

^req R[1-4],\d+$

DEMO DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM