正则表达式需要先创建一个pattern,然后再用这个对象去match一个字符串,然后程序会把匹配的字串存储在matcher对象,你可以通过find屈遍历这个matcher,得到每一个子串。以下是我写的样例程序:
String content = "%1.gif%fdjalkfd%2.gif%fasdafsd";
Pattern pattern = Pattern.compile("%.*?%");
Matcher matcher = pattern.matcher(content);
while (matcher.find()) {
String group = matcher.group();
System.out.format("I found the text \"%s\" starting at index %d " +
"and ending at index %d.%n",
group, matcher.start(), matcher.end());
String tem = "<img src=\"../face/" + group.substring(1,group.length()-1) + "\"/>";
content = content.replace(group, tem);
}
System.out.println(content);
还要注意string对象的replace方法不会修改对象本身,返回的string对象才是修改过的。