[英]match pattern in RegEx in js
我想编辑一个模式,检查文本是否以number/s开头并以number/s或运算符结尾,并根据 test() 方法返回 true 或 false。
我怎么能用JavaScript做到这一点?
var str= "123+125",str2 = "123",str3 = "123*";
let RegularExpression = /^\d*(\d*|(\+|\-|\*|\/){1,})$/; //this pattern variable what I want to edit because it doesn't do what I want.
let result1 = RegularExpression.test(str);
let result2 = RegularExpression.test(str);
let result2 = RegularExpression.test(str);
您可以使用重复 1 次或多次匹配 1 个或多个数字,可选地后跟一个运算符。
^(?:\d+[+*/-]?)+
解释
^
字符串开头(?:
非捕获组
\d+[+*/-]?
匹配 1+ 位可选地后跟+
*
/
-
)+
关闭非捕获组并重复 1+ 次 let pattern = /^(?:\d+[+*/-]?)+$/m; [ "123+125", "", "123", "123*", "123+125-1" ].forEach(s => console.log(s + " --> " + pattern.test(s)));
试试这个模式/^(\d*|[+/*-]?){1,}$/
var str= "123+125",str2 = "123",str3 = "123*"; let RegularExpression = /^(\d*|[+/*-]?){1,}$/; //this pattern variable what I want to edit because it doesn't do what I want. let result1 = RegularExpression.test(str); let result2 = RegularExpression.test(str); let result3 = RegularExpression.test(str); console.log("res1:",result1,",res3:",result2,",res3:",result3)
利用
/^\d+([-+*\/]\d+)*[-+*\/]?$/
见证明
解释:
NODE EXPLANATION
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
\d+ digits (0-9) (1 or more times (matching
the most amount possible))
--------------------------------------------------------------------------------
( group and capture to \1 (0 or more times
(matching the most amount possible)):
--------------------------------------------------------------------------------
[-+*\/] any character of: '-', '+', '*', '\/'
--------------------------------------------------------------------------------
\d+ digits (0-9) (1 or more times (matching
the most amount possible))
--------------------------------------------------------------------------------
)* end of \1 (NOTE: because you are using a
quantifier on this capture, only the LAST
repetition of the captured pattern will be
stored in \1)
--------------------------------------------------------------------------------
[-+*\/]? any character of: '-', '+', '*', '\/'
(optional (matching the most amount
possible))
--------------------------------------------------------------------------------
$ before an optional \n, and the end of the
string
JavaScript:
var str= "123+125",str2 = "123",str3 = "123*"; let RegularExpression = /^\d+([-+*\/]\d+)*[-+*\/]?$/; console.log( RegularExpression.test(str) ); console.log( RegularExpression.test(str2) ); console.log( RegularExpression.test(str3) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.