如何使用正则表达式测试url字符串

时间:2021-09-07 21:39:57

Below is my code

以下是我的代码

/config\/info\/newplan/.test(string)

which will return true when find /config/info/newplan/ in string.

当在字符串中找到/ config / info / newplan /时,它将返回true。

However, I would like to test different condition in the same time like below

但是,我想在同一时间测试不同的条件,如下所示

/config\/info\/newplan/.test(string) || /config\/info\/oldplan/.test(string) || /config\/info\/specplan/.test(string)

which will return true if the string end up with either "newplan" or "oldplan" or "specplan"

如果字符串以“newplan”或“oldplan”或“specplan”结尾,则返回true

My question is how to make a better code and not write "/config/\info/\xxxx\ so many times?

我的问题是如何制作更好的代码而不是多次写“/ config / \ info / \ xxxx \”?

2 个解决方案

#1


1  

Use an alternation group:

使用替换组:

/config\/info\/(?:new|old|spec)plan/.test(string)
                ^^^^^^^^^^^^^^^ 

See the regex demo.

请参阅正则表达式演示。

Pattern details:

  • config\/info\/ - a literal config/info/ substring
  • config \ / info \ / - 文字配置/信息/子串

  • (?:new|old|spec) - a non-capturing group (where | separates alternatives) matching any one of the substrings: new, old or spec
  • (?:new | old | spec) - 匹配任何一个子串的非捕获组(其中|分隔备选方案):new,old或spec

  • plan - a literal plan substring
  • 计划 - 文字计划子字符串

#2


1  

this would be your bet

这将是你的赌注

config\/info\/(newplan|oldplan|specplan)\/
OR
config\/info\/(newplan|oldplan|specplan)\/.test(string)

please see the example at [https://regex101.com/r/NyP1HP/1] as it doesn't allow other possibilities like following

请参阅[https://regex101.com/r/NyP1HP/1]上的示例,因为它不允许其他可能性如下

/config/info/new1plan/
/config/info/newoldplan/
/config/info/specplan1/

#1


1  

Use an alternation group:

使用替换组:

/config\/info\/(?:new|old|spec)plan/.test(string)
                ^^^^^^^^^^^^^^^ 

See the regex demo.

请参阅正则表达式演示。

Pattern details:

  • config\/info\/ - a literal config/info/ substring
  • config \ / info \ / - 文字配置/信息/子串

  • (?:new|old|spec) - a non-capturing group (where | separates alternatives) matching any one of the substrings: new, old or spec
  • (?:new | old | spec) - 匹配任何一个子串的非捕获组(其中|分隔备选方案):new,old或spec

  • plan - a literal plan substring
  • 计划 - 文字计划子字符串

#2


1  

this would be your bet

这将是你的赌注

config\/info\/(newplan|oldplan|specplan)\/
OR
config\/info\/(newplan|oldplan|specplan)\/.test(string)

please see the example at [https://regex101.com/r/NyP1HP/1] as it doesn't allow other possibilities like following

请参阅[https://regex101.com/r/NyP1HP/1]上的示例,因为它不允许其他可能性如下

/config/info/new1plan/
/config/info/newoldplan/
/config/info/specplan1/