您可以使用String.prototype.match()提取這些數字,但是您必須使用g
標誌,因爲您將提取多個數字,並且String.prototype.match()
在全局搜索(如果您計劃使用捕獲)時失敗。您可以使用自定義匹配功能:
var text = "| | Serial: N/A | | UserID: 132382474 | |\
| | Serial: N/A | | UserID: 132382474 | |\
| | Serial: N/A | | UserID: 132382474 | |\
| | Serial: N/A | | UserID: 131046468 | |";
function match(string, regex) {
var matches = [];
var match = null;
while (match = regex.exec(string)) {
matches.push(match[1]);
}
return matches;
}
var numbers = match(text, /UserID:\s(\d*)?/g);
console.log(numbers);
正則表達式的說明:
capture only the numbers -> 132382474
/-\
/UserID:\s(\d*)?/g g -> global search, search multiple times
\______________/
|
search this pattern -> UserID: 132382474
這是必要的,你通過圖案g
標誌,否則while
會創建一個無限循環。
或者只是確保使用其他功能的模式有g
標誌。這樣,您可以在沒有g
標誌的情況下傳遞模式。 global()
函數將檢查模式。如果它缺少g
標誌,它會自動添加它。
var text = "| | Serial: N/A | | UserID: 132382474 | |\
| | Serial: N/A | | UserID: 132382474 | |\
| | Serial: N/A | | UserID: 132382474 | |\
| | Serial: N/A | | UserID: 131046468 | |";
function match(string, regex) {
var regex \t = global(regex);
var matches \t = [];
var match \t = null;
while (match = regex.exec(string)) {
matches.push(match[1]);
}
return matches;
}
function global(re) {
var pattern \t = re.source;
var flags \t = re.global ? re.flags : re.flags += "g";
return new RegExp(pattern, flags);
}
var numbers = match(text, /UserID:\s(\d*)?/);
console.log(numbers);
有幾種方法。你有沒有嘗試過自己?你有沒有聽說過['split'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split)? –
我不確定如何使用那個對不起 –
然後閱讀一些例子。嘗試一些事情。你必須嘗試想法。沒有人會爲你寫代碼。 –