如果我有一个正则表达式,我如何返回它找到的子字符串? 我确定我一定遗漏了一些明显的东西,但我发现了各种方法来确认该子字符串包含在我正在搜索的字符串中,或者用其他东西替换它,但不返回我发现的内容.
最佳答案
Matcher matcher = Pattern.compile("a+").matcher("bbbbaaaaabbbb");
if(matcher.find())
System.out.println(matcher.group(0)); //aaaaa
如果你想要特定的部分
Matcher matcher = Pattern.compile("(a+)b*(c+)").matcher("bbbbaaaaabbbbccccbbb");
if(matcher.find()){
System.out.println(matcher.group(1)); //aaaaa
System.out.println(matcher.group(2)); //cccc
System.out.println(matcher.group(0)); //aaaaabbbbcccc
}
第 0 组是完整的模式。其他组在正则表达式 (
a+)
b*(
c+)
并且可以单独获取
关于java - 返回使用正则表达式找到的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8752215/