所以我已经尽力了:
/\d+([+-/*.])\d{0}/g
希望它与例如 55-匹配(但是当任何数学运算符后面没有数字时)但它与55-匹配, 即使运算符后面有一些数字。(例如:55-5它选择了前三个字符,但你可以看到它后面有“5”。)
如果你能帮助我感激不尽!
这也是我关于stackoverflow的第一个问题。
所以我已经尽力了:
/\d+([+-/*.])\d{0}/g
希望它与例如 55-匹配(但是当任何数学运算符后面没有数字时)但它与55-匹配, 即使运算符后面有一些数字。(例如:55-5它选择了前三个字符,但你可以看到它后面有“5”。)
如果你能帮助我感激不尽!
这也是我关于stackoverflow的第一个问题。
{0}并不意味着“这之后应该正好是 0”,每个 regex101
{0} 与前一个标记完全匹配零次(导致标记被忽略)
您还忘记在您的部分中转义-and 。\[ ]
这是您的原始正则表达式:https ://regex101.com/r/JGnJe7/1/
对整个字符串使用这个正则表达式/^\d+([+\-\/*.])$/。
const matchString = str => str.match(/^\d+([+\-\/*.])$/);
const fiftyfivedash = "55-";
const fiftyfivedashfive = "55-5";
console.log(matchString(fiftyfivedash));
console.log(matchString(fiftyfivedashfive));
/^\d+([+\-\/*.])$/意思是:https ://regex101.com/r/SDrDJx/1
^)开始$)处结束如果您不想要整个字符串,可以使用一些替代方法:
const matchString = str => str.match(/\d+[+\-\/*.](?!\d)/g);
const matchStringOther = str => str.match(/\d+[+\-\/*.](?=\D|$)/g);
const fiftyfivedash = "hello 55- 4+ 66*";
const fiftyfivedashfive = "55-5 45-2 456+2";
console.log(matchString(fiftyfivedash));
console.log(matchString(fiftyfivedashfive));
console.log(matchStringOther(fiftyfivedash));
console.log(matchStringOther(fiftyfivedashfive));
/\d+[+\-\/*.](?!\d)/g表示:https ://regex101.com/r/sDgGTV/1
?),除 (the !) 之外的任何内容:一个数字g)/\d+[+\-\/*.](?=\D|$)/g表示:https ://regex101.com/r/HZayTg/1
?),或者下一个字符不是数字,或者没有更多字符($表示字符串的结尾)g)