在工作中遇到需求如标题所示
- 例如:获取
This is an #apple#.
public static void getFirstContent(String s) {
Pattern p = Pattern.compile("(?<=#).*(?=#)");
Matcher m = p.matcher(s);
m.find();
System.out.println(m.group());
}
//调用
getFirstContent("This is an #apple#.");
- 获取多个匹配的字符串
public static void getAllContent(String s) {
// Pattern p = Pattern.compile("(?:#).*(?:#)");
// Pattern p = Pattern.compile("(?<=#).*(?=#)");
Pattern p = Pattern.compile("#.*?#");
Matcher m = p.matcher(s);
while (m.find()){
System.out.println(m.group());
}
}
//调用
getAllContent("This is an #apple#. But I like #pears#.");