我需要你的帮助来处理一些正则表达式和字符串匹配。我该如何去检查我的字符串(用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 }
出众!无论如何也要抓住整数的值吗? – BobbyJones
是的,一旦你有了一个匹配,你可以得到最后一个字符,并用'+':'+ str.substr(-1)'作为数字。更一般地,你可以用'String#match'方法来抓取匹配:'str.match(/ - (\ d)$ /)[1]'。但请注意,当匹配不匹配时,匹配返回null。 – trincot
@BobbyJones你可以使用RegExp捕获组 – Cheloide