/** * * @author Zen Johnny *@date April 29, 2018 at 4:51:08 PM * */ package demo.regex; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexGetDemo { public static void getDemo(String string, String regex) { //step1: Encapsulate the rules into objects Pattern pattern = Pattern.compile(regex); //step2: Associate the regular object with the string to be extracted, and get the matching (device) engine object Matches matches = pattern.matcher (string); while(matcher.find()) {//Continuously use the regular engine to find objects that match the regular expression, found: true; not found: false System.out.println("start:" + matcher.start() + " word:" + matcher.group() + " end:" + matcher.end()); //Return a substring currently found, and return the start() and end() of its word } } public static void main(String args[]) { //Extract words with more than 3 consecutive letters //hint: \b: word boundary; \B non-word boundary String string = "ming tian jiu yao fang jia la,da jia~"; String regex = "\\b[a-zA-Z]{3,}\\b"; getDemo(string,regex); /* ming tian jiu yao fang Jia Jia */ } }