简体   繁体   English

匹配第 n 个字符之前和之后的组

[英]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.我想匹配第 n 个字符之前的所有内容(第一个字符除外)及其之后的所有内容。 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.之后的所有字符都可以是 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您的正则表达式组没有给出正确的结果,因为([^\\/]*\\/){3}您正在重复捕获的组,这将覆盖先前匹配的组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.量词{3}重复捕获组 3 次,这将具有最后一次迭代的值。

The first iteration will match / , the second firstname/ and the third (the last iteration) lastname/ which will be the value of the group.第一次迭代将匹配/ ,第二个firstname/和第三个(最后一次迭代) lastname/这将是组的值。

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.第二组捕获匹配[^.]* ,它将匹配 0+ 而不是不考虑数据结构的文字点。

If you want to match the full pattern, you could use:如果要匹配完整模式,可以使用:

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

Explanation解释

  • ^ Start of string ^字符串开始
  • ( Capture group 1 (捕获组 1
  • ) Close group )关闭群组
  • \\/ Match / \\/匹配/
  • ( Capture group 2 (捕获组 2
    • [^\\/]+ Match 1+ times not / [^\\/]+匹配 1+ 次而不是/
    • (?:\\/[^\\/]+)+ Repeat 1+ times matching / and 1+ times not / to match the pattern of the rest of the string. (?:\\/[^\\/]+)+重复 1+ 次匹配/和 1+ 次不匹配/以匹配字符串其余部分的模式。
  • ) 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查看示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM