java通过模式匹配,获取匹配到的字符串

时间:2021-06-29 05:49:41
 

/** * java中获取模式匹配的倒的内容 * pattern →欲获取的字符串的规则 * matcher →通过规则进行匹配 * list →用来存储匹配到的内容 * matcher.find() 如果为true则表示匹配到了 * matcher.group()表示匹配到的内容,以字符串的形式返回 */ public static void getMyOrder(){ 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); for(int i=0;i<list.size();i++){ System.out.println(list.get(i)); } }




 
 

public static void ttt(){ String str = "no pains . no Gains."; Pattern pattern = Pattern.compile("(\\w)*"); //[a-zA-Z_0-9] Matcher matcher = pattern.matcher(str); List<String> list = new ArrayList<String>(); int size = 0,length; String temp; String result = "" ; while(matcher.find()){ temp = matcher.group(); list.add(temp); length = temp.length(); if(length > size){ size = length ; result = temp; } } System.out.println(list); System.out.println(result); }