2017-09-26 3 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] '。しかし、 'match'は一致がないときに' 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桁 "を意味します。周囲の '-'と' $ 'はすでに2番目の数字は許されていなくてもかまいません。しかし、たとえそうでないとしても、{1}は事を変えないでしょう。 – trincot

関連する問題