检查字符串是否以

dit*_*tto 1 javascript regex

我想检查一个字符串是否以

- v{number}
Run Code Online (Sandbox Code Playgroud)

所以例如

hello world           false
hello world - v2      true
hello world - v       false
hello world - v88     true
Run Code Online (Sandbox Code Playgroud)

不完全确定如何去做这个 RegEx。

var str = 'hello world - v1';
var patt = new RegExp("/^ - v\d*$/");
var res = patt.test(str);
console.log(res);
Run Code Online (Sandbox Code Playgroud)

我怎么能修复上面的正则表达式?

fed*_*qui 5

一开始就使用它而不检查任何其他东西

- v\d+$
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以确保它以后- v跟至少一位数字结尾。在https://regex101.com/r/pB6vP5/1 中实时查看

然后,您的表达式需要是:

var patt = new RegExp("- v\\d+$");
Run Code Online (Sandbox Code Playgroud)

正如anubhava在另一个答案中所述

  • 不需要 /
  • 需要双重转义\d