2017-09-26 30 views
-1

我需要你的帮助来处理一些正则表达式和字符串匹配。我该如何去检查我的字符串(用var str表示)是否在最后有一个破折号和一个整数?请看下面的例子:检查一个字符串是否在它的末尾有一个破折号整数

Example 1: 

var str = "test101-5" 

evaluate the str and check if it end with a dash and an integer { returns true } 

Example 2: 

var str = "ABC-DEF-GHI-4" 

evaluate the str and check if it end with a dash and an integer { returns true } 


Example 3: 

var str = "test101" 

evaluate the str and check if it end with a dash and an integer { returns false } 

回答

4

您可以使用.test()与下面的正则表达式:

var str = "ABC-DEF-GHI-4"; 
 
console.log(/-\d$/.test(str)); // true 
 

 
str = "test101"; 
 
console.log(/-\d$/.test(str)); // false

$将需要匹配的字符串末尾只发生。

+0

出众!无论如何也要抓住整数的值吗? – BobbyJones

+0

是的,一旦你有了一个匹配,你可以得到最后一个字符,并用'+':'+ str.substr(-1)'作为数字。更一般地,你可以用'String#match'方法来抓取匹配:'str.match(/ - (\ d)$ /)[1]'。但请注意,当匹配不匹配时,匹配返回null。 – trincot

+0

@BobbyJones你可以使用RegExp捕获组 – Cheloide

0

您可以使用捕获组获取最后一位数字。

const 
 
    regex = /-(\d)$/, 
 
    tests = [ 
 
    'test101-5', 
 
    'ABC-DEF-GHI-4', 
 
    'test101' 
 
    ]; 
 
    
 
tests.forEach(test => { 
 
    const 
 
    // Index 0 will have the full match text, index 1 will contain 
 
    // the first capture group. When the string doesn't match the 
 
    // regex, the value is null. 
 
    match = regex.exec(test); 
 
    
 
    if (match === null) { 
 
    console.log(`The string "${test}" doesn't match the regex.`); 
 
    } else { 
 
    console.log(`The string "${test}" matches the regex, the last digit is ${match[1]}.`); 
 
    } 
 
});

正则表达式执行以下操作:

-  // match the dash 
( // Everything between the brackets is a capture group 
    \d // Matches digits only 
) 
$  // Match the regex at the end of the line. 
+0

'{1}'是不必要的。 '\ d'已经意味着“一位数字”。周围的'-'和'$'已经不需要秒数了。但即使不是这样,'{1}'也不会改变一件事情。 – trincot

相关问题