java正则表达式实现获取http后面的内容
时间: 2023-10-02 21:12:01 浏览: 43
可以使用正则表达式来获取 HTTP 链接中的内容,具体实现如下:
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HttpRegexDemo {
public static void main(String[] args) {
String url = "http://www.example.com/index.html?id=123";
Pattern pattern = Pattern.compile("http://[^\\s]+/[^\\s?]+\\?id=(\\d+)");
Matcher matcher = pattern.matcher(url);
if (matcher.find()) {
String id = matcher.group(1);
System.out.println("ID: " + id);
}
}
}
```
在上述代码中,我们使用了正则表达式 `http://[^\\s]+/[^\\s?]+\\?id=(\\d+)` 来匹配 HTTP 链接中的内容。其中,`[^\\s]+` 表示非空字符,`[^\\s?]+` 表示非空字符直到遇到 `?` 字符,而 `(\\d+)` 则表示匹配数字并将其捕获为一个组。
如果匹配成功,我们可以使用 `matcher.group(1)` 方法来获取第一个捕获组中的内容,即 HTTP 链接中的 ID 值。