java8 查找字符串里面第二次出现的冒号内容
可以使用正则表达式来查找字符串中第二次出现的冒号内容。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str = "abc:def:ghi:jkl:mno:pqr";
String pattern = ".*?:.*?:(.*?):";
Pattern regex = Pattern.compile(pattern);
Matcher matcher = regex.matcher(str);
if (matcher.find()) {
String result = matcher.group(1);
System.out.println(result);
}
}
}
输出:
jkl
上述代码中,首先定义了一个字符串 str,其中包含多个冒号。然后定义了一个正则表达式 pattern,使用.*?:.*?:(.*?):来匹配第二个冒号后的内容。接下来,使用 Pattern 类的 compile 方法将正则表达式编译为一个 Pattern 对象。然后,使用 Matcher 类的 matcher 方法将字符串和 Pattern 对象进行匹配。最后,使用 find 方法查找字符串中是否有匹配的内容,如果有,则使用 group 方法获取匹配的结果,即第二个冒号后的内容
原文地址: https://www.cveoy.top/t/topic/hWdB 著作权归作者所有。请勿转载和采集!