正则表达式匹配 java

问题描述

我正在尝试使用正则表达式从 url 中提取以下部分,但未找到任何匹配项。任何人都可以看看我做错了什么吗?

这是网址:

https://www.pinterest.com/pin/700943129497635499/sent/?invite_code=ba8f1ef48e1747199003308cdc92bbb9&sender=773000860950082435&sfo=1

我想提取

https://www.pinterest.com/pin/700943129497635499

我的代码是:

url="https://www.pinterest.com/pin/700943129497635499/sent/?invite_code=ba8f1ef48e1747199003308cdc92bbb9&sender=773000860950082435&sfo=1";
final Pattern pattern = Pattern.compile("https://www\\.pinterest\\.com/pin/.*/",Pattern.DOTALL);
final Matcher matcher = pattern.matcher(url);
url = matcher.group(1);
System.out.println(url);

上面写着java.lang.IllegalStateException: No successful match so far

解决方法

  • 您应该在使用 matcher.find() 之前调用 matcher.group()

  • 带有 .* 的正则表达式导致包含匹配 /sent/ 部分。您可以改用 https:\\/\\/www.pinterest.com\\/pin\\/\\w+\w 代表 [a-zA-Z0-9_] 或者您可以使用 \d+ 仅匹配数字值

  • 其他问题与 matcher.group(1) 部分有关。正则表达式 (...) 中没有捕获组。所以如果你使用 group(1) 那么你会得到一个例外。如果您使用带括号 (https:\\/\\/www.pinterest.com\\/pin\\/\\w+) 的正则表达式,那么您可以使用 matcher.group(1)


String url = "https://www.pinterest.com/pin/700943129497635499/sent/?invite_code=ba8f1ef48e1747199003308cdc92bbb9&sender=773000860950082435&sfo=1";
final Pattern pattern = Pattern.compile("https:\\/\\/www.pinterest.com\\/pin\\/\\w+");
final Matcher matcher = pattern.matcher(url);
if (matcher.find()) {
    url = matcher.group();
    System.out.println(url);
}

输出:

https://www.pinterest.com/pin/700943129497635499