[英]JavaScript Regex Global Match Groups
更新:這個問題是一個近似重復這
我確信我的問題的答案就在那里,但我找不到簡潔的語言來表達它。 我正在嘗試使用 JavaScript 正則表達式執行以下操作:
var input = "'Warehouse','Local Release','Local Release DA'";
var regex = /'(.*?)'/g;
console.log(input.match(regex));
// Actual:
// ["'Warehouse'", "'Local Release'", "'Local Release DA'"]
// What I'm looking for (without the '):
// ["Warehouse", "Local Release", "Local Release DA"]
有沒有一種干凈的方法可以用 JavaScript 正則表達式來做到這一點? 很顯然,我可以帶出的'
s ^自己,但我正在尋找與正則表達式來caputre全局匹配分組的正確方法。
要使用正則表達式執行此操作,您需要使用.exec()
對其進行迭代以獲得多個匹配的組。 帶有 match 的g
標志只會返回多個完整匹配項,而不是您想要的多個子匹配項。 這是一種使用.exec()
。
var input = "'Warehouse','Local Release','Local Release DA'";
var regex = /'(.*?)'/g;
var matches, output = [];
while (matches = regex.exec(input)) {
output.push(matches[1]);
}
// result is in output here
工作演示: http : //jsfiddle.net/jfriend00/VSczR/
對字符串中的內容有一定的假設,你也可以使用這個:
var input = "'Warehouse','Local Release','Local Release DA'";
var output = input.replace(/^'|'$/, "").split("','");
工作演示: http : //jsfiddle.net/jfriend00/MFNm3/
有一個名為String.prototype.matchAll()
的 ECMAScript 提案可以滿足您的需求。
不是很通用的解決方案,因為 Javascript 不支持lookbehind,但是對於給定的輸入,這個正則表達式應該可以工作:
m = input.match(/([^',]+)(?=')/g);
//=> ["Warehouse", "Local Release", "Local Release DA"]
String.prototype.matchAll
現在在現代瀏覽器和Node.js 中得到很好的支持。 這可以像這樣使用:
const matches = Array.from(myString.matchAll(/myRegEx/g)).map(match => match[1]);
注意傳入的RegExp
必須有全局標志,否則會拋出錯誤。
方便的是,當沒有找到匹配項時,這不會引發錯誤,因為.matchAll
總是返回一個迭代器(與.match()
返回null
)。
對於這個特定的例子:
var input = "'Warehouse','Local Release','Local Release DA'";
var regex = /'(.*?)'/g;
var matches = Array.from(input.matchAll(regex)).map(match => match[1]);
// [ "Warehouse", "Local Release", "Local Release DA" ]
嘗試使用input.replace(regex, "$1")
來獲取捕獲組的結果。
使用 es2020,您可以使用matchAll
:
var input = "'Warehouse','Local Release','Local Release DA'";
var regex = /'(.*?)'/g;
const match_all = [...input.matchAll(regex)];
如果您正在使用打字稿,請不要忘記在tsconfig.json
進行設置:
"compilerOptions": {
"lib": ["es2020.string"]
}
這個正則表達式有效,但具有定義的字符......
var input = "'Warehouse','Local Release','Local Release DA'";
var r =/'[\w\s]+'/gi;
console.log(input.match(regex));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.