字符串:@:21101001@+@:21101002@+@:21101003@+@:21101004@
需提取所有 @: 與 @ 之間的數字串,結果為:["21101001", "21101002", "21101003", "21101004"]。
const str = '@:21101001@+@:21101002@+@:21101003@+@:21101004@';
const numbers = str.match(/@:(\d+)@/g); // 帶 g 标志匹配所有
// 結果: ["@:21101001@", "@:21101002@", "@:21101003@", "@:21101004@"]
// 需進一步提取純數字:
const pureNumbers = str.match(/@:(\d+)@/g).map(s => s.slice(2, -1));
// 或使用捕獲組 + replace:
const result = str.replace(/@:(\d+)@/g, '$1').split('+');
// 結果: ["21101001", "21101002", "21101003", "21101004"]
const str = '@:21101001@+@:21101002@+@:21101003@+@:21101004@';
const regex = /@:(\d+)@/g;
const matches = [...str.matchAll(regex)];
const numbers = matches.map(m => m[1]); // m[1] 是第一個捕獲組
console.log(numbers); // ["21101001", "21101002", "21101003", "21101004"]
const str = '@:21101001@+@:21101002@+@:21101003@+@:21101004@';
const regex = /@:(\d+)@/g;
const numbers = [];
let match;
while ((match = regex.exec(str)) !== null) {
numbers.push(match[1]);
}
console.log(numbers);
/@:(\d+)@/g
│ │ │ ││
│ │ │ └─ 字面量 '@' 結束邊界
│ │ └──── 捕獲組:一個或多個數字 (\d+)
│ └─────── 字面量 ':'
└───────── 字面量 '@' 開始邊界
g ──────── 全局匹配所有出現
| 輸入字符串 | 結果 | 說明 |
|---|---|---|
@:123@ | ["123"] | 單個匹配 |
@:123@abc@:456@ | ["123", "456"] | 非目標字符被忽略 |
@:@ | [] | \d+ 要求至少一位數字 |
@:12a3@ | [] | 非純數字不匹配 |
無匹配內容 | null (match) / [] (matchAll) | 需判空處理 |
function extractNumbersBetweenMarkers(str, startMarker = '@:', endMarker = '@') {
if (!str) return [];
// 轉義特殊字符構建安全正則
const escapedStart = startMarker.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const escapedEnd = endMarker.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const regex = new RegExp(`${escapedStart}(\\d+)${escapedEnd}`, 'g');
const matches = [...str.matchAll(regex)];
return matches.map(m => m[1]);
}
// 使用
const input = '@:21101001@+@:21101002@+@:21101003@+@:21101004@';
console.log(extractNumbersBetweenMarkers(input));
// ["21101001", "21101002", "21101003", "21101004"]
使用 /@:(\d+)@/g 配合 String.prototype.matchAll() (現代) 或 RegExp.prototype.exec() 循環 (兼容) 是提取此類標記間數字的標準、高效方案。