Frage

The regex is:

/^\/node?(?:\/(\d+)(?:\.\.(\d+))?)?/

I can understand that / in the beginning and the end are regex delimiters, also ^\/node is for a string starting with /node What's happening after that beats me!

War es hilfreich?

Lösung

You should look into getting a tool like RegexBuddy. It will explain everything in a given regex, as well as how it compiles and how it branches.

Assuming PCRE or similar:

   /                    //begin
        ^               //start of string
        \/              //literal /
        node?           //I assume node is optional, normally it'd be (node)?
                        //? makes the previous expression optional
        (
             ?:         //non-capturing group (think of it like dont capture <this>)
             \/         //literal /
             (\d+)      // one or more digits, 0-9
             (
                  ?:    // another non-capturing group
                  \.\.  // literal ..
                  (\d+) // one or more digits 0-9
             )
             ?         // optional once more
        )
        ?              // make the previous group optional
    /                  // end

Andere Tipps

? anything following this is "optional"

(?: non-capturing group

\/ escaped /

(\d+) -more than 1 digit - also in a capture group "()"

(?: again

\. - escaped .

\. - again

(\d+) - same as before

)?)? - not sure - what flavour of regex is this?

You are correct, the / at the start are pattern delimiters. Lets remove those for simplicity

^\/node?(?:\/(\d+)(?:\.\.(\d+))?)?

The (?:...) is a non-capturing group. This is a group that does not get grabbed into a match group. This is an optimisation, let's remove the ?: to make the pattern clearer.

^\/node?(\/(\d+)(\.\.(\d+))?)?

The \ is an escape character, so \/ is actually just a / but as these denote the start and end of the pattern then need to be escaped. The . matches (almost) any character so it needs to be escaped too.

The ? makes the receding pattern optional, so ()? means whatever is in the brackets appears zero or one times.

  • ^ denotes the start of the string
  • \/node? matches /node or /nod
  • \/(\d+) matches / followed by one or more digits (the \d+). The digits are captured into the first match group
  • (\.\.(\d+))? matches .. followed by one or more digits (the \d+). The digits are captured into the second match group
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top