检查字符串是否在其末尾有一个破折号整数

时间:2017-09-26 20:34:59

标签: javascript regex string

我需要你的一些正则表达式和字符串匹配的帮助。我如何检查我的字符串(由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 }

2 个答案:

答案 0 :(得分:4)

您可以将.test()与以下正则表达式一起使用:

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

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

$将要求匹配仅发生在字符串的末尾。

答案 1 :(得分: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.