简体   繁体   English

获取除JavaScript正则表达式中的match之外的所有内容

[英]Get everything except match in javascript regular expression

I have the following regex to get the first part after a url: 我有以下正则表达式来获取网址后的第一部分:

^http[s]?:\/\/.*?\/([a-zA-Z-_.%]+).*$

It matches test in the below urls: 它与以下网址中的test匹配:

foo.com foo.com
http://foo.com http://foo.com
http://foo.com/ test http://foo.com/ 测试
http://foo.com/ test / http://foo.com/ 测试 /
http://foo.com/ test ?bar http://foo.com/ 测试 ?bar

What I'm now trying to do is recreate the same url, but replace test with a different value. 我现在想做的是重新创建相同的URL,但是用不同的值替换test Either by taking the parts before and after the match or reversing the result. 通过在比赛之前或之后取出零件或反转结果。

I'm sure there's a regexy way of doing this, but I'm unable to find out how to do so. 我敢肯定有一种正规的方法可以做到这一点,但是我不知道该怎么做。

You can use a capturing group for part before /test and use it as back-reference in replacement: 您可以在/test之前将捕获组用于零件,并将其用作替换中的后向参考:

var re = /^(https?:\/\/[^\/]+\/)[^?\/]+/gmi; 
var subst = '$1foobar'; 

var result = str.replace(re, subst);

[^?\\/]+ will match text before next / or ? [^?\\/]+将匹配下一个/?之前的文本? after domain name in URL. 网址中的域名之后。 As your original regex it also assumes that URLs start with http:// or https:// . 作为原始正则表达式,它还假定URL以http://https://开头。

RegEx Demo 正则演示

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

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