【问题标题】:Get characters after the third forward slash ("/") - using regex在第三个正斜杠(“/”)之后获取字符 - 使用正则表达式
【发布时间】:2017-04-20 00:18:36
【问题描述】:

我一直在尝试从字符串的第三个正斜杠 ("/") 之后获取子字符串。

http://www.google.com/search?q=Regular+Expressions 之前停止?和 # 如果它们存在于字符串中。

我有正则表达式:

Pattern regex = Pattern.compile(":\\/\\/[0-9a-zA-Z-\\.:]+(\\/)([^?#]*)$");

但它不适用于每个字符串

我也想出了正则表达式:

Pattern regex = Pattern.compile("(.*)?:\\/\\/[^#?]*);

但是,这个会在第三个正斜杠(“/”)之前抓取所有内容。

我做错了什么? 谢谢

【问题讨论】:

  • 显示两种情况的示例输出(# 和 ?)
  • 当您说“不适用于每个字符串”时,请显示您测试的内容
  • 另外,你真的需要正则表达式吗? indexOfsubstring 可能工作得很好
  • 使用字符串“google.com/hello?test#”,它应该只抓住 /hello 避免 ?和 # 个字符。我已经用这些字符串google.com/hellogoogle.com/search?q=Regular+Expressions&num=1000”“google.com:80/#”进行了测试。仅当 # 被删除时,它才部分适用于最后一个字符串
  • 那里甚至没有 3 个/ :)

标签: java regex


【解决方案1】:

你可以试试

(?:.*?\/){3}([^\/?#]+)

或者在java中

(?:.*?\\/){3}([^\\/?#]+)

(转义的反斜杠)。

匹配任何内容,包括斜线 - 三倍。然后捕获所有内容,包括斜线、问号或井号。

结果在捕获组 1 中。

Check it out here at regex101.

【讨论】:

    【解决方案2】:

    这个正则表达式可以在 java 中工作:

        public static void main(String[] args) throws Exception {
        String s = "http://www.google.com/search?q=Regular+Expressions";
        String regex = "(?:.*?/){2}.*?(/\\w+)(\\?|#).*"; // Don't capture anything upto the 3rd "/" then capture everything until you get a "?" or a "#" and then don't capture the rest. Replace everything with the captured value
        String str = s.replaceAll(regex, "$1");
        System.out.println(str);
        String s2 = "https://www.google.com/hello?test#";
        String str2 = s2.replaceAll(regex, "$1");
        System.out.println(str2);
    
    }
    

    O/P:

    /search
    /hello
    

    【讨论】:

      猜你喜欢
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      • 1970-01-01
      • 1970-01-01
      • 2011-08-09
      • 1970-01-01
      • 2019-08-26
      相关资源
      最近更新 更多