在做完“ 写一个正则表达式,可以匹配尾号5连的手机号。规则: 第1位是1,第二位可以是数字3458其中之一, 后面4位任意数字,最后5位为任意相同的数字。
* 例如:18601088888、13912366666”这道题后,我又用常规代码做了一次,希望可以得到大家的指教……
如果能不用正则再优化请指教……
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- /**
- * 9、 写一个正则表达式,可以匹配尾号5连的手机号。规则: 第1位是1,第二位可以是数字3458其中之一, 后面4位任意数字,最后5位为任意相同的数字。
- * 例如:18601088888、13912366666
- *
- * @author Administrator
- *
- */
- public class Test9Demo {
- public static void main(String[] args) throws IOException {
- while (true) {
- BufferedReader br = new BufferedReader(new InputStreamReader(
- System.in));
- System.out.println("请输入手机号");
- String num = br.readLine();
- System.out.println(match(num));
- }
- }
- public static boolean match(String num) {
- char x = num.charAt(10);
- if (num.length() == 11) { // 判断是否是11位
- if (num.startsWith("13") || num.startsWith("14")
- || num.startsWith("15") || num.startsWith("18")) { // 判断是否是13,14,15或18开头
- if (loop(num,x)) { // 判断最后五位是否都一样
- return true;
- }
- }
- }
- return false;
- }
- public static boolean loop(String num,char x) {
- String s = num.substring(6,11);
- char[] ch = s.tocharArray();
- for (char cha : ch) {
- if (cha != x) {
- // 最后五位有不相同的
- return false;
- }
- }
- // 最后五位都相同
- return true;
- }
- }