2017-09-26 43 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

相關問題