正则表达式(补充)

前端之家收集整理的这篇文章主要介绍了正则表达式(补充)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在做完“ 写一个正则表达式,可以匹配尾号5连的手机号。规则: 第1位是1,第二位可以是数字3458其中之一, 后面4位任意数字,最后5位为任意相同的数字。

* 例如:18601088888、13912366666”这道题后,我又用常规代码做了一次,希望可以得到大家的指教……

如果能不用正则再优化请指教……


  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4.  
  5. /**
  6. * 9、 写一个正则表达式,可以匹配尾号5连的手机号。规则: 第1位是1,第二位可以是数字3458其中之一, 后面4位任意数字,最后5位为任意相同的数字。
  7. * 例如:18601088888、13912366666
  8. *
  9. * @author Administrator
  10. *
  11. */
  12. public class Test9Demo {
  13. public static void main(String[] args) throws IOException {
  14. while (true) {
  15. BufferedReader br = new BufferedReader(new InputStreamReader(
  16. System.in));
  17. System.out.println("请输入手机号");
  18. String num = br.readLine();
  19. System.out.println(match(num));
  20. }
  21. }
  22.  
  23. public static boolean match(String num) {
  24. char x = num.charAt(10);
  25. if (num.length() == 11) { // 判断是否是11位
  26. if (num.startsWith("13") || num.startsWith("14")
  27. || num.startsWith("15") || num.startsWith("18")) { // 判断是否是13,14,15或18开头
  28. if (loop(num,x)) { // 判断最后五位是否都一样
  29. return true;
  30. }
  31. }
  32. }
  33. return false;
  34. }
  35.  
  36. public static boolean loop(String num,char x) {
  37. String s = num.substring(6,11);
  38. char[] ch = s.tocharArray();
  39. for (char cha : ch) {
  40. if (cha != x) {
  41. // 最后五位有不相同的
  42. return false;
  43. }
  44. }
  45. // 最后五位都相同
  46. return true;
  47. }
  48. }



猜你在找的正则表达式相关文章