import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexUtil { public static void main(String args[]){ //原始字符串 String expression = "<!--[CDATA[formRelated(CreatorUserLogin.Person.CompanyDepartment.Location.Organization)-->role(SimResManagerCity)]]-->"; String formRelatedType = "formRelated"; String roleType = "role"; System.out.println(getContent(formRelatedType,expression)); System.out.println(getContent(roleType,expression)); } public static String getContent(String type,String expression){ //正则表达式//(([^)]*)//) (,表示我要抽取的第一个左括号 //([^)]*),其中[^)]*表示从左括号开始算起,直至遇到右括号之前的所有字符,然后还加上了分组符号(),是为了把括号里的字符定义为一个组,方便后面的抽取 String regStr = type+"//(([^)]*)//)"; Pattern pattern = Pattern.compile(regStr); Matcher matcher = pattern.matcher(expression); while(matcher.find()){ //此时拿到的group1,就是在上面定好的组,对应了括号里面的内容 return matcher.group(1); } return null; } }