public class TestRegMock {
public static String getMatcher(String regex, String source) {
String result = "";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(source);
while (matcher.find()) {
result = matcher.group(0);
}
return result;
}
public static void main(String[] args) {
String url = "ip=10.112.178.177,port=7001,state=online,offset=6984163,lag=0";
//截取ip 截取 ip= 到,间的字符串
String regex3 = "(?<=ip=).*?(?=,)";
System.out.println(getMatcher(regex3, url));
//截取port port=到 ,间的字符串
String regex4 = "(?<=port=).*?(?=,)";
System.out.println(getMatcher(regex4, url));
}
}
正则截取规则内的文本
最新推荐文章于 2023-12-06 17:03:38 发布
该博客展示了如何使用Java的正则表达式进行字符串截取。`getMatcher`函数通过编译正则模式并使用`Matcher`对象找到匹配的子串,例如从URL字符串中提取`ip`和`port`信息。示例代码演示了如何截取`ip`和`port`字段直到逗号之间的内容。
摘要由CSDN通过智能技术生成