简体   繁体   English

正则表达式:我正在编写一个正则表达式以匹配子字符串并返回url部分的其余部分

[英]Regex: i am writing a regular expression to match substring and return rest of the part of url

i have a url something like http://www.abc.def/bill/part1/part2 on which perforing regex which checks for bill and returns the rest part of the url ie bill/part1/part2 我有一个类似http://www.abc.def/bill/part1/part2的网址,其上的穿孔正则表达式会检查bill并返回网址的其余部分,即bill/part1/part2

Below the code which i am trying to make work "http://www.abc.def/bill/part1/part2".match(/^bill\\:(.*)$/gm) 下面的代码,我试图使工作"http://www.abc.def/bill/part1/part2".match(/^bill\\:(.*)$/gm)

Answer 回答

With validation ("http://www.abc.def/bill/part1/part2".match(/bill(.*)$/gm) || [])[0] 具有验证("http://www.abc.def/bill/part1/part2".match(/bill(.*)$/gm) || [])[0]

You use URL constructor and can check .pathname of the URL 您使用URL构造函数,并且可以检查URL的.pathname

 let url = new URL("http://www.abc.def/bill/part1/part2"); if (/\\/bill\\//.test(url.pathname)) console.log(url.pathname.slice(1)); 

Removing front carat ^ and \\: worked for you 去除前克拉 ^\\:为您服务

Explanation 说明

  • bill to match string starting from bill bill匹配从bill开始的字符串
  • (.*)$ matches rest of the input till end of string (.*)$匹配其余输入,直到字符串结尾

Demo 演示版

 var output = "http://www.abc.def/bill/part1/part2".match(/bill(.*)$/gm) console.log(output); 

You can just match anything after (and including) bill : 您可以匹配(包括) bill之后的任何内容:

 console.log( 'http//:www.abc.def/bill/part1/part2' .match(/bill(.*)/)[0] ) 

But using proper URL parsing with the URL object (see answer by guest271314 ) or a library like url-parse would likely be a better approach: 但是对URL对象(请参见guest271314的答案 )或类似url-parse的库使用正确的URL解析可能是一种更好的方法:

 console.log( urlParse( 'http://www.abc.def/bill/part1/part2' ).pathname.slice(1) ) 
 <script src="https://wzrd.in/standalone/url-parse@latest"></script> 

Your regex ^bill\\:(.*)$ does not match bill/part1/part2 because you use an anchor ^ to assert the position at the start of the string. 您的正则表达式^bill\\:(.*)$bill/part1/part2不匹配,因为您使用锚^来声明字符串开头的位置。 You also specify \\: after bill , but : is not present after bill in the example. 您还可以在bill后面指定\\: bill但是在示例中在bill后面没有:。

If you want to return bill/part1/part2 , you could use bill.*$ without the capturing group (.*) . 如果要返回bill/part1/part2 ,则可以使用bill.*$而不使用捕获组(.*)

 var match = "http://www.abc.def/bill/part1/part2".match(/bill.*$/); console.log(match[0]); 

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

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