简体   繁体   中英

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.

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

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

在此处输入图片说明

 let str = `/firstname/lastname/some/cool/name` let op = str.match(/^.([^/]+\\/[^/]+)\\/(.*)$/) console.log(op)

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

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

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

See example

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