1、它们都是对表达式的记法,因此也被称为前缀记法、中缀记法和后缀记法。它们之间的区别在于运算符相对与操作数的位置不同:前缀表达式的运算符位于与其相关的操作数之前;中缀和后缀同理。
中缀形式的算术表达式A+(B-C/D)*E的后缀形式是什么?手工运算怎么算啊?
先根据中缀表达式构造二叉树,运算符为根!中缀表达式是先遍历左子树,接着是根,最后是右子树,如此递归!所以,原表达式中,A是左子树,+是根,+右边的一大坨都是右子树那一大坨分三部分(B-C/D)*E,*是根,左右两部分就分别是左右子树B-C/D中B是左子树,-是根,C/D是右子树,然后就是C/D了,/是根,C、D分别是右子树如图:然后后序遍历该二叉树,即可得到后缀表达式:A B C D / - E * +
2、正则表达式
*表示匹配0-无穷; +表示匹配1-无穷。
3、Java正则表达式类Pattern和Matcher
Pattern类主要用于编译正则表达式之后创建一个匹配模式;Matcher类使用Pattern实例提供的模式信息对正则表达式进行匹配。
Pattern类:
Pattern complie(String regex)
由于Pattern的构造函数是私有的,不可以直接创建,所以通过静态方法compile(String regex)方法来创建,将给定的正则表达式编译并赋予给Pattern类
-
String pattern()
返回正则表达式的字符串形式,其实就是返回Pattern.complile(String regex)的regex参数
Pattern compile(String regex, int flags) 方法功能和compile(String regex)相同,不过增加了flag参数
int flags() 返回当前Pattern的匹配flag参数. flag参数用来控制正则表达式的匹配行为。
- Pattern.matcher(CharSequence input) 对指定输入的字符串创建一个Matcher对象
- 例如:Pattern pattern = Pattern.compile("\\?{2}"); Matcher matcher = pattern.matcher("??"); boolean matches = matcher.matches();// true
-
String[] split(CharSequence input) String[] split(CharSequence input, int limit)
-
String[] split(CharSequence input, int limit 功能和String[] split(CharSequence input)相同,增加参数limit目的在于要指定分割的段数
-
Pattern.quote(String s) 返回给定的字符串的字面量。
- matches()方法编译给定的正则表达式并且对输入的字串以该正则表达式为模开展匹配,该方法适合于该正则表达式只会使用一次的情况,也就是只进行一次匹配工作,因为这种情况下并不需要生成一个Matcher实例。
- Matcher类
- boolean matches() 最常用方法:尝试对整个目标字符展开匹配检测,也就是只有整个目标字符串完全匹配时才返回真值.
Pattern pattern = Pattern.compile
("\\?{2}");Matcher matcher = pattern.matcher("??");
boolean matches = matcher.matches();//true
System.out.println(matches);
matcher=pattern.matcher("?");
matches = matcher.matches();//false
System.out.println(matches);
- boolean lookingAt() 对前面的字符串进行匹配,只有匹配到的字符串在最前面才会返回true
Pattern p = Pattern.compile
("\\d+");Matcher m = p.matcher("22bb23");
boolean match = m.lookingAt();//true
System.out.println(match);
m = p.matcher("bb2233");
match= m.lookingAt();System.out.println(match);//false
- boolean find() 对字符串进行匹配,匹配到的字符串可以在任何位置
Pattern p = Pattern.compile
("\\d+");Matcher m = p.matcher("22bb23");
m.find();// 返回true
Matcher m2 = p.matcher("aa2223");
m2.find();// 返回true
Matcher m3 = p.matcher("aa2223bb");
m3.find();// 返回true
Matcher m4 = p.matcher("aabb");
m4.find();// 返回false
- int start() 返回当前匹配到的字符串在原目标字符串中的位置
- int end() 返回当前匹配的字符串的最后一个字符在原目标字符串中的索引位置.
- String group() 返回匹配到的子字符串 Pattern.start(),Pattern.end(),Pattern.group()代码示例
Pattern p = Pattern.compile
("\\d+");Matcher m = p.matcher("aa22bb23");
m.find();
int start = m.start();//2
String group = m.group();//22
int end = m.end();//4
System.out.println(start);
System.out.println(group);
System.out.println(end);
-
-
-
-
-