我需要从下面的链接中提取ID:
shipments/8891cbf6-f3d4-4369-9ae0-fdb794a8b61d/documents/routingLabel
https://example1.com/service/document-generation-service/retrieve/J75pYky-5kAreVLVrmR2sYf-svE0abvqW8QDdQg44CFMUj6YtsxveeAQY8iJX_cgeb1OV4vFfZBohGSngpIb3Q/addressLabel
http://example2.com/service/document-generation-service/retrieve/J75pYky-5kAreVLVrmR2sYf-svE0abvqW8QDdQg44CFMUj6YtsxveeAQY8iJX_cgeb1OV4vFfZBohGSngpIb3Q/addressLabel
这些是来自上面链接的ID:
8891cbf6-f3d4-4369-9ae0-fdb794a8b61d
J75pYky-5kAreVLVrmR2sYf-svE0abvqW8QDdQg44CFMUj6YtsxveeAQY8iJX_cgeb1OV4vFfZBohGSngpIb3Q
J75pYky-5kAreVLVrmR2sYf-svE0abvqW8QDdQg44CFMUj6YtsxveeAQY8iJX_cgeb1OV4vFfZBohGSngpIb3Q
我写了2个正则表达式来提取这些id,但是不知道如何将它们组合为一个。
这是第一种类型shipments\/(.*?)\/
。
这是第二种和第三种类型的链接:
document-generation-service\/retrieve\/(.*?)\/
我可以将它们组合为一个适用于所有类型链接的正则表达式吗?
答案 0 :(得分:2)
是的,您可以使用|
(或)来组合它们:
(shipments|document-generation-service\/retrieve)\/(.*?)\/
您的令牌ID现在将在捕获的#2组中
查看以下所有链接的结果:
const urls = [
"shipments/8891cbf6-f3d4-4369-9ae0-fdb794a8b61d/documents/routingLabel",
"https://example1.com/service/document-generation-service/retrieve/J75pYky-5kAreVLVrmR2sYf-svE0abvqW8QDdQg44CFMUj6YtsxveeAQY8iJX_cgeb1OV4vFfZBohGSngpIb3Q/addressLabel",
"http://example2.com/service/document-generation-service/retrieve/J75pYky-5kAreVLVrmR2sYf-svE0abvqW8QDdQg44CFMUj6YtsxveeAQY8iJX_cgeb1OV4vFfZBohGSngpIb3Q/addressLabel"
],
ids = urls.map(url => url.match(/(shipments|document-generation-service\/retrieve)\/(.*?)\//)[2]);
console.log(ids); // List of id's retrieved from the above URLS