| 用途 | 正則 | 說明 / 範例 |
|---|---|---|
| 匹配中文字元 | [\u4e00-\u9fa5] | 基本漢字區 |
| 匹配雙位元組字元 | [^\x00-\xff] | 含中文、全形符號;可用於計算字串視覺長度 |
| 匹配空白行 | \n\s*\r | 含空白字元的空行 |
| 匹配 HTML 標籤 | /<(.*)>.*<\/\1>|<(.*) \/>/ | 簡易匹配,巢狀標籤不適用 |
| 匹配首尾空白 | (^\s*)|(\s*$) | 可實作 trim |
| IPv4 位址 | (\d+)\.(\d+)\.(\d+)\.(\d+) | 四段數字,需額外驗證 0-255 |
String.prototype.len = function() {
return this.replace(/[^\x00-\xff]/g, "aa").length;
};
String.prototype.trim = function() {
return this.replace(/(^\s*)|(\s*$)/g, "");
};
function IP2V(ip) {
var re = /(\d+)\.(\d+)\.(\d+)\.(\d+)/g;
if (re.test(ip)) {
return RegExp.$1*Math.pow(255,3) + RegExp.$2*Math.pow(255,2) + RegExp.$3*255 + RegExp.$4*1;
} else {
throw new Error("Not a valid IP address!");
}
}
備註:現代環境建議使用 ip.split('.').reduce((acc, oct) => acc*256 + +oct, 0) 更簡潔高效。
𠮷),請使用 \p{Script=Han}(需支援 Unicode 屬性的引擎,如 ES2018+、Java 9+、.NET Core)。