正则表达式除了匹配一串字符串是否符合某种格式,还能从文本中过滤出一些匹配的字串。
如:从字符串"Test127.0.0.1Test1127.0.0.2Test111127.0.0.3Test4"中过滤得到IP地址(127.0.0.1,127.0.0.2,127.0.0.3)
如:从字符串"Test127.0.0.1Test1127.0.0.2Test111127.0.0.3Test4"中过滤得到IP地址(127.0.0.1,127.0.0.2,127.0.0.3)
String str = "Test127.0.0.1Test1127.0.0.2Test111127.0.0.3Test4"; //源字符串
Pattern pattern = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"); //正则表达式匹配格式
Matcher matcher = pattern.matcher(str);
List<String> list = new ArrayList<String>();
while(matcher.find())
{
String srcStr = matcher.group(); //这里得到的ip
list.add(srcStr); //将匹配的结果放入List
}
System.out.println(list);