繁体   English   中英

如何将两个正则表达式组合成一个具有不同 $1 的正则表达式?

[英]How to combine two regular expressions into one with different $1?

我有两个具有不同 $1 的正则表达式。 在第一部分中,$1 之前有一个斜线,但在第二部分中没有斜线。 那么如何将它们组合成一个表达式呢?

 const url = 'http://localhost////example///author/admin?query=1212'; clean_url = url.replace(/($|\?)/, "/$1").replace(/([^:]\/)\/+/g, "$1") console.log(clean_url)

由于此问题询问的是@nuxtjs/redirect-module ,因此您可以使用多个重定向:

redirect: [{
  from: '(.*)($|\?)(.*)',
  to: '$1/$2$3'
}, {
  from: '(.*)([^:]\/)\/+(.*)',
  to: '$1$2$3'
}]

或更换 function

redirect: [{
  from: '.*(?:(?:$|\?)|(?:[^:]\/\/+)).*',
  to: from => from.replace(/($|\?)/, "/$1").replace(/([^:]\/)\/+/g, "$1")
}]

您可以使用

 const url = 'http://localhost////example///author/admin'; clean_url = url.replace(/($|\?)|([^:]\/)\/+/g, (x,y,z) => z? z: '/' + y); console.log(clean_url); // => http://localhost/example/author/admin/

($|\?)|([^:]\/)\/+正则表达式匹配

  • ($|\?) - 第 1 组 ( y ):字符串结尾或?
  • | - 或者
  • ([^:]\/)\/+ - 除:/ (Group 2, z ) 之外的任何字符,然后是一个或多个斜杠。

如果 Group 2 匹配,则替换为 Group 2 值,否则,替换为/ + Group 3 值。

仅仅“组合”这两个正则表达式是不可能的,但您可以组合这些任务,因为两者都只是插入一个/具有不同的条件。

您可以将逻辑与 lookbehinds 结合起来(这可能还不是在每个浏览器中都可用)并且表达式是令人厌恶的,我会小心生产中的性能; 但这是可能的;)

 const url = 'http://localhost////example///author/admin?query=1212'; clean_url = url.replace(/(?<?\.?*)(:<?[:\/])(??\/+|\/*(,=\.)|\/*$)/g, "/") console.log(clean_url)

暂无
暂无

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

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