Stephan
Stephan

Reputation: 1999

Match group before nth character and after that

I want to match everything before the nth character (except the first character) and everything after it. So for the following string

/firstname/lastname/some/cool/name

I want to match

Group 1: firstname/lastname
Group 2: some/cool/name

With the following regex, I'm nearly there, but I can't find the correct regex to also correctly match the first group and ignore the first /:

([^\/]*\/){3}([^.]*)

Note that I always want to match the 3rd forward slash. Everything after that can be any character that is valid in an URL.

Upvotes: 2

Views: 335

Answers (3)

The fourth bird
The fourth bird

Reputation: 163207

The quantifier {3} repeats 3 times the capturing group, which will have the value of the last iteration.

The first iteration will match /, the second firstname/ and the third (the last iteration) lastname/ which will be the value of the group.

The second group captures matching [^.]* which will match 0+ not a literal dot which does not take the the structure of the data into account.

If you want to match the full pattern, you could use:

^\/([^\/]+\/[^\/]+)\/([^\/]+(?:\/[^\/]+)+)$

Explanation

  • ^ Start of string
  • ( Capture group 1
  • ) Close group
  • \/ Match /
  • ( Capture group 2
    • [^\/]+ Match 1+ times not /
    • (?:\/[^\/]+)+ Repeat 1+ times matching / and 1+ times not / to match the pattern of the rest of the string.
  • ) Close group
  • $ End of string

Regex demo

Upvotes: 0

Code Maniac
Code Maniac

Reputation: 37755

Your regex group are not giving proper result because ([^\/]*\/){3} you're repeating captured group which will overwrite the previous matched group Read this

You can use

^.([^/]+\/[^/]+)\/(.*)$

enter image description here

let str = `/firstname/lastname/some/cool/name`

let op = str.match(/^.([^/]+\/[^/]+)\/(.*)$/)

console.log(op)

Upvotes: 1

Yaelet
Yaelet

Reputation: 160

Ignoring the first /, then capturing the first two words, then capturing the rest of the phrase after the /.

^(:?\/)([^\/]+\/[^\/]+)\/(.+)

See example

Upvotes: 0

Related Questions