简体   繁体   English

匹配正斜杠后的最后一个或多个数字

[英]Matching the last digit or digits after a forward slash

In a JavaScript function in my Rails app, I'm trying to get the id of a recipe. 在我的Rails应用程序的JavaScript函数中,我正在尝试获取配方的ID。 Looking inside the event object like this 查看这样的事件对象

 e.delegateTarget.baseURI

produces the uri, the last number of which (after the forward slash) is the id I want. 产生uri,其中最后一个数字(在正斜杠之后)是我想要的id。

http://myroute.com/users/2/recipes/6

Of course, that id could be much longer in the future, so I need to be able to get all the digits after the last forward slash. 当然,将来这个id可能要长得多,所以我需要能够在最后一个正斜杠之后得到所有数字。

I tried to get the last id this way 我试着用这种方式获得最后一个id

var uri = e.delegateTarget.baseURI
var re = /^(.*[\\\/\d])/;
var recipe_id = uri.match(re);

The matched slash is supposed to be the last one because .* matches greedily, and then I look for any digit. 匹配的斜杠应该是最后一个因为。*匹配贪婪,然后我寻找任何数字。 This is all wrong. 这都错了。 I'm not very experienced with regular expressions. 我对正则表达式不太熟悉。 Can you help? 你能帮我吗?

A very simple way to do this would be to use string.split() 一个非常简单的方法是使用string.split()

var uri = "http://myroute.com/users/2/recipes/6",
    splituri = uri.split('/');

recipe_id = splituri[splituri.length - 1] // access the last index

Edit: 编辑:

Even easier with the .pop() method, which returns the popped value 使用.pop()方法更容易,它返回弹出的值

like elclanrs said. 像elclanrs说的那样。

var uri = e.delegateTarget.baseURI,
    recipe_id = uri.split('/').pop();

You should use the special character $ , which means end of input: 你应该使用特殊字符$ ,这意味着输入结束:

re = /\d+$/; //matches one or more digits from the end of the input

Here is a good resource on JavaScript regular expressions. 是JavaScript正则表达式的一个很好的资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM