1

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?

James Donnelly
  • 117,312
  • 30
  • 193
  • 198
runtimeZero
  • 22,318
  • 19
  • 63
  • 115
  • 2
    Your mostly correct; between the slashes there must be at least one character (any character will do). That's what the `+` quantifier means ("one or more"), as opposed to `*` ("zero or more"). – Pointy Aug 12 '14 at 13:59
  • http://tinyurl.com/oqe28ez – Roko C. Buljan Aug 12 '14 at 14:00
  • `REGEX_STRING_REGEXP`? The purpose is obvious from name. – dfsq Aug 12 '14 at 14:00
  • Looks like a regex to match SEO friendly URIs like `/directory_01/` or `/directory_01/file` – Reeno Aug 12 '14 at 14:02
  • possible duplicate of [Reference - What does this regex mean?](http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) – Mathletics Aug 12 '14 at 14:12

2 Answers2

2

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:

Example

Direct link to Regexper result.

James Donnelly
  • 117,312
  • 30
  • 193
  • 198
1

regex: /^/(.+)/([a-z]*)$/

^ : anchor regex to start of line

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

([a-z]*) : 0 or more instances of any single lowercase character a-z

$ : 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 a-z. Lastly, since both (.+) and ([a-z]*) 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 ^/(.+)/([a-z]*)$ 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).

Chris
  • 758
  • 4
  • 11