简体   繁体   English

正则表达式匹配带有五个正斜杠的字符串

[英]Regex to match string with five forward slashes

I want to write a regex to match any string with 5 forward slashes in. This is to match a URL in Google Analytics.我想编写一个正则表达式来匹配任何带有 5 个正斜杠的字符串。这是为了匹配 Google Analytics 中的 URL。 I thought I had gotten close, but no cigar yet.我以为我已经接近了,但还没有雪茄。 This is what I've come up with:这是我想出的:

\/.*\/.*\/.*\/.*\/.*$

But it doesn't match anything.但它不匹配任何东西。 How can I correct this?我该如何纠正? Or is it not possible?或者不可能?

The following regex will work :以下正则表达式将起作用

.*(?:\/.*){5}

Explanation:解释:

.*             # Any character (except newlines) 0 or more times
   (?:         # Start of non-capturing group
      \/       # Matches `/` literally (is esacped with a backslash)
        .*     # Any character (except newlines) 0 or more times
          )    # End of group
           {5} # The previous group five times

If you want just something like /aaa/bbb/ccc/ddd/, this will make the trick: /[^/]+/[^/]+/[^/]+/[^/]+/ However, there are more things to consider?如果你只想要像 /aaa/bbb/ccc/ddd/ 这样的东西,这将成功: /[^/]+/[^/]+/[^/]+/[^/]+/ 但是,有还有更多的事情要考虑吗?

  1. Is this the only format accepted?这是唯一接受的格式吗?
  2. Is it possible to have any chain of characters before the first slash?在第一个斜杠之前是否可以有任何字符链?
  3. Is it possible to have any chain of characters after the last slash?最后一个斜杠后是否可以有任何字符链?

If this one doesn't fit your needs, you as might as well provide some valid and invalid inputs.如果这不符合您的需求,您不妨提供一些有效和无效的输入。

Cheers.干杯。

您可以使用 "(\\w*\\W){5}",因为 "\\W" 用于非单词字符。

Simple like this:简单像这样:

(/[^/]*){5}

Change * to + if you need at least a character between slashes.如果您需要在斜杠之间至少有一个字符,请将 * 更改为 +。

I need to pull out links only have just string with excluding numbers and queries in URL in Google Analytics.我需要拉出链接只有字符串,不包括谷歌分析中 URL 中的数字和查询。

so, I need this URL所以,我需要这个网址

www.site.com/en/rent/cairo/apartments-for-rent/ www.site.com/en/rent/cairo/apartments-for-rent/

and exclude these并排除这些

www.website.com/en/buy/apartment-for-sale-in-acacia-compound-new-cairo-947145/

  www.website.com/en/buy/apartment-for-sale-in-acacia-compound-new-cairo-947145/?price=1000

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

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