我需要你的幫助來處理一些正則表達式和字符串匹配。我該如何去檢查我的字符串(用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