[size=small]第一次在工作中使用正则表达式,记录下来:
group( )方法仅返回匹配的部分。
split( )方法是指将以正则表达式为界,将字符串分割成String数组。
通常这两个方法结合起来使用:[/size]
group( )方法仅返回匹配的部分。
split( )方法是指将以正则表达式为界,将字符串分割成String数组。
通常这两个方法结合起来使用:[/size]
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GroupSplitTest {
public static void main(String[] args) {
//目的:将str字符串按时间分组,并以时间为键,节目为值存入map中。
Map<String, String> map = new TreeMap<String, String>();
String str = "04:58 见证 05:28 走近科学(精编版) 06:11
焦点访谈 06:24 轻松十分:2007-31 06:33 法治在线";
Pattern pattern = Pattern.compile("(\\d{1,2}:\\d{1,2})");
//split方法获取的为以正则表达式为界的字符串数组,不包括正则表达式,在这里存的为各个节目名。
String[] strs = pattern.split(str);
Matcher matcher = pattern.matcher(str);
//find()与group()结合使用
matcher.find();
for(int i=1;i<strs.length;i++){
//group方法获取的是正则表达式匹配的部分。
map.put(matcher.group(), strs[i]);
matcher.find();
}
System.out.println(map);
}
}
1475

被折叠的 条评论
为什么被折叠?



