The concept of regular expressions
- Definition: An expression that conforms to a certain rule
- Function: Used to specialize in manipulating strings
Features: For some specific symbols to represent the operation of the Code, thus simplifying the lengthy program code
- Benefit: simplifies complex manipulation of strings
Cons: The more symbols are defined, the longer the regular, the worse the reading
Key classes
- String
- Pattern: Regular Class object
- Matcher: The engine class that performs a matching operation on the character sequence by interpreting the pattern. (Matching device)
Specific operation function Matching: Returns Boolean value that matches the rule
1 String: boolean string.matches(String regex)2 Pattern + Matcher: Pattern pattern.compile(String regex) Matcher pattern.matcher(String regex) boolean matcher.matches()3 Pattern boolean b = Pattern.matches(String regex, String string)
Cut: Returns a string other than the match rule
1 String:String[] split(String regex)2 String:String[] split(String regex, int limit)> 为了让规则的结果被重用,可以让规则封装成一个组,用()完成。组的出现都有编号: 从1开始想要使用已有的组可以通过格式:\ + 组序号 Eg:以叠词作为分隔符号,切隔字符串:(.)\1+ Eg: (X(Y(Z)))(M) 组号:1 2 3 4
Replace: Returns the string replaced by the rule
1 String:String replaceAll(String regex, String replacement):regex-\n2 String:String replaceFirst(String regex, String replacement):replacement-$n3 Pattern + Matcher: Pattern pattern.compile(String regex) Matcher pattern.matcher(String regex) ------------------------------------- String matcher.quoteReplacement(String s) String matcher.replaceAll(String replacement)
Get: Remove a substring of a rule in a string
将正则表达式封装成对象;让正则表达式和要操作的字符串相关联;关联后,获取正则匹配引擎;通过引擎对符合规则的子串进行操作,如:取出1 //step1:将规则封装成对象 Pattern pattern = Pattern.compile(regex); //step2:让正则对象和要提取的字符串相关联,获取匹配(器)引擎对象 Matcher matcher = pattern.matcher(string); while(matcher.find()) {//不断地利用正则引擎查找符合正则表达式的对象,找到:true;没有找到:false System.out.println("start:" + matcher.start() + " word:" + matcher.group() + " end:" + matcher.end());//返回当前查找到的一个子串,并返回其单词的开始start()与结束区间end() }
Reference documents
[黑马程序员_毕向东_Java基础视频教程第25天](http://www.huahuionline.com/MainCtrl?page=ShowLessonDetailPage&lesson_id=56c1838945ceb61ab5246f3d&cNo=1)
Regular expression one of Java se: overview