简体   繁体   English

使用javascript正则表达式捕获组

[英]Capture groups with javascript regex

I have a url string from which I want to capture all the words between the / delimiter: 我有一个URL字符串,我想从中捕获/分隔符之间的所有单词:

So given this url: 因此,鉴于此网址:

"/way/items/add_items/sell_items":

I want to capture: 我要捕获:

way
items
sell_items
add_items

If I do it like this: 如果我这样做:

'/way/items/sell_items/add_items'.match(/(\w+)/g)
=> [ 'way', 'items', 'sell_items', 'add_items' ]

It will give me an array back but with no capturing groups, why I do this instead: 它会给我一个数组,但是没有捕获组,为什么要这样做:

new RegExp(/(\w+)/g).exec("/way/items/sell_items/add_items")
=> [ 'way', 'way', index: 1, input: '/way/items/sell_items/add_items' ]

But this only captures way .. I want it to capture all four words. 但这只是捕获方式..我希望它捕获所有四个词。

How do I do that? 我怎么做?

Thanks 谢谢

You should write 你应该写

var parts = url.split("/");

The global flag is used to the replace method. global标志用于replace方法。
Also, it makes the exec method start from the last result (using the RegExp 's lastIndex property) 另外,它使exec方法从最后一个结果开始(使用RegExplastIndex属性)

If you need by some reasons an exactly Regex, so use this, else use split() function. 如果由于某些原因需要精确的正则表达式,请使用此函数,否则请使用split()函数。

Code: 码:

var re = new RegExp(/\w+?(?=\/|$)/gi);  // added |$
alert(re);
var text = '/way/items/add_items/sell_items';
var aRes = text.match(re);

Result: [way, items, add_items, sell_items]; 结果: [方式,项目,add_items,sell_items];

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

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