[英]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.