正则表达式的使用
对参考答案的学习
1.通过正则表达式提取需要的内容
下面代码就将一个负数a+bi中的数字a和b提取出来,从而拿来参与运算。
Pattern pattern=Pattern.compile("([-]?[0-9]+)(\\+)([-]?[0-9]+)(i)");
Matcher matcher=pattern.matcher(string);
while(matcher.find()){
a1=Integer.parseInt(matchera.group(1));
b1=Integer.parseInt(matchera.group(3));
}
2.”([-]?[0-9]+)(\+)([-]?[0-9]+)(i)”
()用来记录子表达式;即([-]?[0-9]+) 、 (\+) 、 ([-]?[0-9]+) 、 (i)分别是四个子表达式
group(0)是整个表达式
group(1) group(2) group(3) group(4)分别是上述四个表达式
[-]?[0-9]+ 表示负数
3.别人的做法
public class Solution {
public String complexNumberMultiply(String a, String b) {
String x[] = a.split("\\+|i");
String y[] = b.split("\\+|i");
int a_real = Integer.parseInt(x[0]);
int a_img = Integer.parseInt(x[1]);
int b_real = Integer.parseInt(y[0]);
int b_img = Integer.parseInt(y[1]);
return (a_real * b_real - a_img * b_img) + "+" + (a_real * b_img + a_img * b_real) + "i";
}
}
机智的别人的做法,学习一些split函数:
split
public String[] split(String regex)
Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
regex是语法;
使用时需注意:
a.如遇特殊字符,需加”\”转义
b.如需要多个分割符,需用“|”连接不同的分隔符
详解见
http://www.cnblogs.com/liubiqu/archive/2008/08/14/1267867.html