正则表达式匹配

前端之家收集整理的这篇文章主要介绍了正则表达式匹配前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


模式匹配

  1. public class Solution {
  2. //(1)调用函数
  3. public boolean match(char[] str,char[] pattern)
  4. {
  5.  
  6. return new String(str).matches(new String(pattern));
  7. }
  8.  
  9. //(2)[正规匹配方式]
  10. public boolean match2(char[] str,char[] pattern) {
  11. if (str == null || pattern == null) {
  12. return false;
  13. }
  14. int strIndex = 0;
  15. int patternIndex = 0;
  16. return matchCore(str,strIndex,pattern,patternIndex);
  17. }
  18.  
  19. public boolean matchCore(char[] str,int strIndex,char[] pattern,int patternIndex) {
  20. //有效性检验:str到尾,pattern到尾,匹配成功
  21. if (strIndex == str.length && patternIndex == pattern.length) {
  22. return true;
  23. }
  24. //pattern先到尾,匹配失败
  25. if (strIndex != str.length && patternIndex == pattern.length) {
  26. return false;
  27. }
  28. //模式第2个是*,且字符串第1个跟模式第1个匹配,分3种匹配模式;如不匹配,模式后移2位
  29. if (patternIndex + 1 < pattern.length && pattern[patternIndex + 1] == '*') {
  30. if ((strIndex != str.length && pattern[patternIndex] == str[strIndex]) || (pattern[patternIndex] == '.' && strIndex != str.length)) {
  31. return matchCore(str,patternIndex + 2)//模式后移2,视为x*匹配0个字符
  32. || matchCore(str,strIndex + 1,patternIndex + 2)//视为模式匹配1个字符
  33. || matchCore(str,patternIndex);//*匹配1个,再匹配str中的下一个
  34. } else {
  35. return matchCore(str,patternIndex + 2);
  36. }
  37. }
  38. //模式第2个不是*,且字符串第1个跟模式第1个匹配,则都后移1位,否则直接返回false
  39. if ((strIndex != str.length && pattern[patternIndex] == str[strIndex]) || (pattern[patternIndex] == '.' && strIndex != str.length)) {
  40. return matchCore(str,patternIndex + 1);
  41. }
  42. return false;
  43. }
  44.  
  45.  
  46. }@H_403_172@

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