简体   繁体   English

正则表达式,用于从URL提取客户/订单号

[英]Regex for customer/order number extraction from URL

I am hoping a regex guru can help to solve my issue, 我希望正则表达式专家可以帮助解决我的问题,

I want to search the following URL's to extract certain pieces of data: 我想搜索以下URL's以提取某些数据:

  • /#!/customers/2848060/orders/9234573/history

    1. I want one regex function to extract the number following 'customers' string (2848060) . 我想要一个正则表达式函数来提取'customers'字符串(2848060)

    2. I want another regex to extract the number following the word 'orders' (9234573) . 我希望另一个正则表达式提取单词'orders' (9234573)

Any help would be massively appreciated. 任何帮助将不胜感激。

I want one regex function to extract the number following 'customers' string (2848060). 我想要一个正则表达式函数来提取“客户”字符串后面的数字(2848060)。

/(?<=customers\/)(.*)(?=\/orders)/g

I want another regex to extract the number following the word 'orders' (9234573). 我希望另一个正则表达式提取单词“ orders”之后的数字(9234573)。

/(?<=orders\/)(.*)(?=\/history)/g

Following is snippet for test 以下是测试片段

 var str = '/#!/customers/2848060/orders/9234573/history' var customer = str.match(/(?<=customers\\/)(.*)(?=\\/orders)/g)[0] var order = str.match(/(?<=orders\\/)(.*)(?=\\/history)/g)[0] console.log(customer); console.log(order); 

Alternative Solution 替代解决方案

I want one regex function to extract the number following 'customers' string (2848060). 我想要一个正则表达式函数来提取“客户”字符串后面的数字(2848060)。

/customers\/(.*)\/orders/

I want another regex to extract the number following the word 'orders' (9234573). 我希望另一个正则表达式提取单词“ orders”之后的数字(9234573)。

/orders\/(.*)\/history/

Following is snippet for test 以下是测试片段

 var str = '/#!/customers/2848060/orders/9234573/history' var customer = str.match(/customers\\/(.*)\\/orders/)[1] var order = str.match(/orders\\/(.*)\\/history/)[1] console.log(customer); console.log(order); 

I want one regex function to extract the number following 'customers' string (2848060) 我想要一个正则表达式函数来提取“客户”字符串后面的数字(2848060)

Use capturing groups 使用捕获组

For customer /customers\\/(\\d+)/ 对于客户 /customers\\/(\\d+)/

var matches = "/#!/customers/2848060/orders/9234573/history".match( /customers\/(\d+)/ );
if (matches)
{
   console.log( "customers " + matches[1] );
}

I want another regex to extract the number following the word 'orders' (9234573). 我希望另一个正则表达式提取单词“ orders”之后的数字(9234573)。

Similarly for orders /orders\\/(\\d+)/ 对于订单 /orders\\/(\\d+)/

Also, you may not need regex if you URL pattern is likely to be the same 另外,如果您的网址格式可能相同,则可能不需要正则表达式

var items = str.split( "/" );
var customers = items[4];
var orders = items[6];
var r = /\d+/g;
var s = "/#!/customers/2848060/orders/9234573/history";
var m;
while ((m = r.exec(s)) != null) {
  alert(m[0]);
}

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

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