2017-12-18 243 views
1

客户/订单数抽取我希望正则表达式大师可以帮助解决我的问题,正则表达式从URL

我想搜索以下URL's提取数据的某些部分:

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

    1. 我想一个正则表达式函数来提取以下'customers'字符串(2848060)数量。

    2. 我想要另一个正则表达式提取单词'orders'(9234573)后面的数字。

任何帮助将大规模赞赏。

+2

我建议你玩https://regex101.com/来建立你的正则表达式。 –

回答

1

我想要一个正则表达式函数来提取'客户' 字符串(2848060)后面的数字。

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

我想另一个正则表达式来提取字后的数字 '订单' (9234573)。

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

以下为测试

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);

替代解决方案片断

我想一个正则表达式函数来提取后面的数字'customers' string(2848060)。

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

我想另一个正则表达式来提取字后的数字 '订单' (9234573)。

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

以下为测试

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);

+0

JS在正则表达式中不支持向后看,仅向前看 – Thomas

+0

可能是我对RegEx的了解有限。你能否指出我的意见解释方向?谢谢。 –

+0

JS中不允许/支持'(?<= ...)'部分。这就是为什么你的片段抛出一个错误 – Thomas

1

片断我想一个正则表达式函数来提取以下 '客户' 字符串(2848060)

使用捕获组

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

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

我想另一个正则表达式来提取字后的数字 '订单' (9234573)。

同样,对于订单/orders\/(\d+)/

此外,你可能不需要正则表达式如果URL模式很可能是同一

var items = str.split("/"); 
var customers = items[4]; 
var orders = items[6]; 
+0

谢谢!我最初使用拆分,但URL可能或不可能有网址的订单部分。这意味着它可能只是/ customers/17264658。 –

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