Java中使用正则表达式匹配出http://192.168.1.185:8080/的的主机
时间: 2024-01-01 11:05:50 浏览: 143
可以使用以下代码实现:
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String url = "http://192.168.1.185:8080/";
Pattern pattern = Pattern.compile("http://([^/:]+)(:\\d*)?/");
Matcher matcher = pattern.matcher(url);
if (matcher.find()) {
String host = matcher.group(1);
System.out.println(host);
}
}
}
```
运行结果为:
```
192.168.1.185
```
解释一下正则表达式的含义:
- `http://`:匹配字符串开始的 `http://`。
- `([^/:]+)`:匹配除了 `/` 和 `:` 以外的字符,用括号把这个匹配的部分括起来,表示这个部分是我们需要的。
- `(\\:\\d*)?`:匹配 `:` 后面跟着 0 个或多个数字的部分,用 `\\` 转义 `:`,加上 `?` 表示这部分是可选的。
- `\\/`:匹配 `/`。
- `/` 后面没有其他字符,表示这个正则表达式只匹配主机部分。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)