检查字符串是否以

时间:2016-07-07 09:40:39

标签: javascript regex

我想检查字符串是否以

结尾
- v{number}

所以例如

hello world           false
hello world - v2      true
hello world - v       false
hello world - v88     true

不完全确定如何进行此RegEx。

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

我如何修复上述RegEx?

2 个答案:

答案 0 :(得分:3)

只需使用此功能而不检查开头的其他内容

- v\d+$

这样您就可以确保它以- v结尾,后跟至少一位数。在https://regex101.com/r/pB6vP5/1

中查看

然后,你的表达必须是:

var patt = new RegExp("- v\\d+$");

作为stated by anubhava in another answer

  • 无需/
  • 要求\d双重转义。



var str = 'hello world - v15';
var patt = new RegExp("- v\\d+$");
var res = patt.test(str);
console.log(res);




答案 1 :(得分:0)

这是一种无需Regex即可实现相同结果的解决方案。值得一试。

function stringEndsWithVersionNum(string) 
{
    var parts   = string.split('- v');
    if(parts[0] !== string) //if the string has '- v' in it
    {
        var number = parts[parts.length -1].trim();//get the string after -v
        return !isNaN(number) && number.length > 0;//if string is number, return true. Otherwise false.
    }
    return false; 
}

请这样使用:

stringEndsWithVersionNum('hello world - v32')//returns true
stringEndsWithVersionNum('hello world - v'); //returns false 
stringEndsWithVersionNum('hello world');     //returns false

相关问题