正则表达式:java获取两个字符中间的字符串

  • 例如:获取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#.");
正则表达式:java获取两个字符中间的字符串_第1张图片

你可能感兴趣的:(java基础)