简体   繁体   English

解码JS正则表达式

[英]decoding a JS regular expression

I am going through some legacy code and I came across this regular express: 我正在浏览一些遗留代码,我遇到了这个常规快递:

var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/; 

I am slightly confused as to what this regular expression signifies. 关于这个正则表达式的含义,我有点困惑。

I have so far concluded the following: 到目前为止,我总结了以下内容:

  1. Begin with / 首先 /
  2. Then any character (numeric, alphabetic, symbols, spaces) 然后任何字符(数字,字母,符号,空格)
  3. then a forward slash 然后是正斜线
  4. End with alphabetic characters 以字母字符结尾

Can someone advice? 有人可以建议吗?

You can use a tool like Regexper to visualise your regular expressions. 您可以使用Regexper之类的工具来显示正则表达式。 If we pass your regular expression into Regexper, we'll be given the following visualisation: 如果我们将正则表达式传递给Regexper,我们将获得以下可视化:

例

Direct link to Regexper result . 直接链接到Regexper结果

regex: /^/(.+)/([az]*)$/ 正则表达式:/^ /(.+)/([az]*)$/

^ : anchor regex to start of line ^:锚定正则表达式开始行

(.+) : 1 or more instances of word characters, non-word characters, or digits (。+):1个或多个单词字符,非单词字符或数字的实例

([az]*) : 0 or more instances of any single lowercase character az ([az] *):任何单个小写字符az的0或更多个实例

$ : anchor regex to end of line $:将正则表达式锚定到行尾

In summary, your regular expression is looking to match strings where it is the first forwardslash, then 1 or more instances of word characters, non-word characters, or digits followed, then another forwardslash, then 0 or more instances of any single lowercase character az. 总之,您的正则表达式寻找匹配的字符串,它是第一个前向闪存,然后是一个或多个单词字符实例,非单词字符或数字后跟,然后是另一个前向闪烁,然后是0或更多任何单个小写字符的实例AZ。 Lastly, since both (.+) and ([az]*) are surrounded in parenthesis, they will capture whatever matches when you use them to perform regular expression operations. 最后,由于括号中包含(。+)和([az] *),因此当您使用它们执行正则表达式操作时,它们将捕获任何匹配项。

I would suggest going to rubular , placing the regex ^/(.+)/([az]*)$ in the top field and playing with example strings in the test string box to better understand what strings will fit within that regex. 我建议去rubular ,将正则表达式^ /(。+)/([az ] *)$放在顶部字段中,并在测试字符串框中使用示例字符串来更好地理解该正则表达式中的字符串。 (/string/something for example will work with your regular expression). (/ string / something例如可以与你的正则表达式一起使用)。

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

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