How could I select a range of characters up until a third / is present and select all if there is no third / using regular expression

Tags: ,



I need to select a range within a string up until the third / is present.

I currently have ^([^/]*/[^/]*/[^/]*/ but this will only work when there is more than 3 / in the string. Ideally I’d need to select all characters up until a third /, and select all if there is no third /

If anyone can think of a way around this that would be great.

Thanks!

Answer

To match substring starting from 3rd occurrence of / where there may be less than 3 /s you may use this regex using range quantifier:

^(?:[^/]*/){0,3}

RegEx Demo

How it works:

  • ^ We start at beginning of a line
  • We are using a greedy quantifier {0,3} to match preceding group 0 to 3 times
  • Inside the group we are matching 0 or more of any characters that are not / followed by a /


Source: stackoverflow