在工作中遇到需求如标题所示
- 例如:获取
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#.");

本文介绍了如何使用正则表达式从文本中提取特定格式的数据,包括单个匹配项及多个匹配项的提取方法。通过具体示例展示了不同正则表达式的应用方式。
816

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



