[英]Return text between brackets and not include brackets
我正在使用以下 regEx 來匹配括號中的文本:
'textA(textB)'.match(/\((.+?)\)/g)
但它返回包含方括號的文本,例如 (textB)
如何返回不帶括號的文本,例如 textB
我假設輸入包含平衡括號。 如果是,則可以使用下面的正則表達式來匹配括號中出現的所有字符。
[^()]+(?=\))
> 'textA(textB)'.match(/[^()]+(?=\))/g)
[ 'textB' ]
說明:
[^()]+
否定的字符類,可匹配任何字符但不匹配(
或)
一次或多次。 (?=\\))
正向超前,它斷言匹配的字符必須后跟右括號)
您必須在括號中用\\
引號將它們括起來\\
'textA(textB)'.match(/\((.+?)\)/g)
如果不這樣做,則將外部括號解釋為正則表達式元字符。
要提取不帶括號的匹配文本:
var match = 'textA(textB)'.match(/\((.+?)\)/); // no "g"
var text = match[1];
創建一個與“ g”(“全局”)限定詞一起使用的正則表達式以匹配並收集括號內的字符串是很.match()
,因為該限定詞會導致.match()
函數的返回值發生變化。 如果不帶“ g”,。 .match()
函數將返回一個數組,該數組的整體匹配項位於位置0,而匹配的組位於后續位置。 但是, 隨着 “G”, .match()
簡單地返回整個表達的所有比賽。
我能想到的唯一方法是重復進行匹配,而我認為最簡單的方法是使用一個函數:
var parenthesized = [];
var text = "textA (textB) something (textC) textD) hello (last text) bye";
text.replace(/\((.+?)\)/g, function(_, contents) {
parenthesized.push(contents);
});
這將在數組中累積正確括號化的字符串“ textB”,“ textC”和“ last text”。 它不會包含“ textD”,因為它沒有正確地加上括號。
可以定義一個將字符串與正則表達式匹配的函數,並通過用戶定義的函數自定義輸出數組。
String.prototype.matchf = function (re, fun) {
if (re == null || re.constructor != RegExp) {
re = new RegExp(re);
}
// Use default behavior of String.prototype.match for non-global regex.
if (!re.global) {
return this.match(re);
}
if (fun == null) { // null or undefined
fun = function (a) { return a[0]; };
}
if (typeof fun != "function") {
throw TypeError(fun + " is not a function");
}
// Reset lastIndex
re.lastIndex = 0;
var a;
var o = [];
while ((a = re.exec(this)) != null) {
o = o.concat(fun(a));
}
if (o.length == 0) {
o = null;
}
return o;
}
用戶定義的函數隨數組一起提供,該數組是RegExp.exec
的返回值。
用戶定義的函數應返回一個值或值的數組。 它可以返回一個空數組,以從結果數組中排除當前匹配項的內容。
當未提供用戶定義的函數fun
時,上述自定義函數的行為應與String.match
相同。 與濫用String.replace
提取數組相比,此方法的開銷應較小,因為不必構造替換的字符串。
回到您的問題,使用上面的自定義函數,您可以將代碼編寫為:
'textA(textB)'.matchf(/\((.+?)\)/g, function (a) {return a[1];});
請matchAll
function。
(你原來的正則表達式就足夠了)
for (const results of 'textA(textB)'.matchAll(/\((.+?)\)/g)) {
console.log(results[0]) // outputs: (textB)
console.log(results[1]) // outputs: textB
}
matchAll()
方法返回所有匹配字符串與正則表達式的結果的迭代器,包括捕獲組; 索引 0 返回整體,並在返回組部分之后進行索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.