【Dart學習】--Dart之正則表達式相關方法總結


一,部分屬性

RegExp exp = new RegExp(r"(\w+)");

  • 返回正則表達式的哈希碼
    print(exp.hashCode);
  • 正則表達式是否區分大小寫
    print(exp.isCaseSensitive);
  • 正則表達式是否匹配多行
    print(exp.isMultiLine);
  • 返回源正則表達式字符串
    print(exp.pattern);
  • 返回對象運行時的類型
    print(exp.runtimeType);

二,常用方法

RegExp exp = new RegExp(r"(\w+)");

  • 返回正則表達式匹配項的可迭代對象
    print(exp.allMatches("abc def ghi"));
  • 搜索並返回第一個匹配項,沒有則返回null
    print(exp.firstMatch(""));
  • 正則表達式是否找到匹配項
    print(exp.hasMatch("as"));
  • 從第幾個字符開始匹配正則表達式
    print(exp.matchAsPrefix("ab cd", 3));
  • 返回正則表達式的第一個匹配字符串
    print(exp.stringMatch("abc de"));
  • 返回正則表達式的字符串表示
    print(exp.toString());

三,實用案例

  • 驗證郵政編碼的正則,返回是否匹配的布爾值
    RegExp postalcode = new RegExp(r'(\d{6})');
    print(postalcode.hasMatch("518000"));
  • 驗證手機號碼的正則,以Iterable< Match >返回所有匹配項
    RegExp mobile = new RegExp(r"(0|86|17951)?(13[0-9]|15[0-35-9]|17[0678]|18[0-9]|14[57])[0-9]{8}");
    Iterable<Match> mobiles = mobile.allMatches("13812345678 12345678901 17012345678");
    for (Match m in mobiles) {
      String match = m.group(0);
     print(match);
    }
  • 驗證網址URL的正則,如果匹配成功以Match返回匹配項,否則返回null
    RegExp url = new RegExp(r"^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+");
    print(url.firstMatch("http://www.google.com"));
  • 驗證身份證號碼的正則,返回第一個匹配的字符串
    RegExp identity = new RegExp(r"\d{17}[\d|x]|\d{15}");
    print(identity.stringMatch("My id number is 35082419931023527x"));

     




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM