简体   繁体   中英

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. If we pass your regular expression into Regexper, we'll be given the following visualisation:

例

Direct link to Regexper result .

regex: /^/(.+)/([az]*)$/

^ : anchor regex to start of line

(.+) : 1 or more instances of word characters, non-word characters, or digits

([az]*) : 0 or more instances of any single lowercase character az

$ : 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. Lastly, since both (.+) and ([az]*) are surrounded in parenthesis, they will capture whatever matches when you use them to perform regular expression operations.

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. (/string/something for example will work with your regular expression).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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