VerbalExpressions 是一個 Dart 套件,旨在透過流暢且易讀的 API 簡化複雜正則表達式的建立。它允許開發者使用直覺的方法鏈逐步建立正則表達式模式,減少錯誤機率並提升程式碼可維護性。適用於解析結構化文字或驗證輸入格式,該套件在保留完整功能的同時,抽象了原始正則表示法的複雜性。此套件支援所有主要平台,使其適用於跨平台應用。
適用情境
文字模式驗證
輸入淨化
從字串中提取資料
解析結構化日誌
構建可重用的正則表達式生成器
主要特色
流暢的、可鏈式呼叫的 API
可讀且可維護的正則表達式建構
支援所有標準正則表達式作業
跨平台相容性
輕鬆整合至Flutter應用
適合對象
開發表單驗證器的開發者
重視程式碼可讀性的團隊
需要動態正則表達式生成的專案
處理使用者輸入或日誌資料的應用程式
使用建議
與原始正則表達式相比,可能會增加輕微開銷
不太適合極其簡單的模式
需要了解基本的正則表達式概念
原始 README
以下為關聯原始碼儲存庫的 README 原文快照,最新內容請造訪原始碼儲存庫。
verbal_expressions
A library for Dart developers that helps to construct difficult regular expressions.
Dart package info is here: https://pub.dartlang.org/packages/verbal_expressions
Quick start
var regex = VerbalExpression()
..startOfLine()
..then("http").maybe("s")
..then("://")
..maybe("www.").anythingBut(" ")
..endOfLine();
// Create an example URLString url = "https://www.google.com";
// Use VerbalExpression's hasMatch() method to test if the entire string matches the regex
regex.hasMatch(url); //True
regex.toString(); // Outputs the regex used: ^http(s)?\\:\\/\\/(www\\.)?([^\\ ]*)\$
var regex = VerbalExpression()..startOfLine()..then("abc")..or("def");
var testString = "defzzz";
//Use VerbalExpression's hasMatch() method to test if parts if the string match the regex
regex.hasMatch(testString); // true
Feel free to use any predefined char groups:
var regex = VerbalExpression()
..wordChar()..nonWordChar()
..space()..nonSpace()
..digit()..nonDigit();
Define captures:
var expression = VerbalExpression()
..find("a")
..beginCapture()..find("b")..anything()..endCapture()
..then("cd");
RegExp regex = expression.toRegExp();
var match = regex.firstMatch(text);
print(match.group(0)); // returns "abcd"print(match.group(1)); // returns "b"