首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

JavaScript 正則表達式提取字符串中 @: 與 @ 之間的數字

     編輯:程式設計疑難解答

問題描述

字符串:@:21101001@+@:21101002@+@:21101003@+@:21101004@
需提取所有 @: 與 @ 之間的數字串,結果為:["21101001", "21101002", "21101003", "21101004"]。

最簡解法:match + 全局正則

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"]

更優雅:matchAll + 解構賦值 (ES2020+)

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"]

傳統 exec 循環(兼容舊環境)

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() 循環 (兼容) 是提取此類標記間數字的標準、高效方案。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved