簡體   English   中英

JS Regex提取括號中的數據

[英]JS Regex extract data in parenthesis

我試圖從字符串中提取$()內的數據。 我的弦看起來像這樣

$(123=tr@e:123)124rt12$(=ttre@tre)frg12<>$(rez45)

基本上,有可能是在$什么()和每$()之間。 但是這里的$()中不能有任何$()。

這是我到目前為止無法正常工作的內容

var reg = new RegExp('\\$\\(.*(?![\\(])\\'), 'g');
var match = reg.exec(mystring);

您可以試試這個\\\\$\\\\([^(]*\\\\)

 var mystring = "$(123=tr@e:123)124rt12$(=ttre@tre)frg12<>$(rez45)" var reg = new RegExp('\\\\$\\\\([^(]*\\\\)', 'g'); console.log(reg.exec(mystring)); console.log(reg.exec(mystring)); console.log(reg.exec(mystring)); 

您可以使用match來收集字符串中正則表達式模式的所有匹配項:

 var mystring = "$(123=tr@e:123)124rt12$(=ttre@tre)frg12<>$(rez45)" var reg = new RegExp('\\\\$\\\\([^(]*\\\\)', 'g'); console.log(mystring.match(reg)); 

要捕獲$()中的所有內容,請使用類似如下的惰性模式: (?:\\$\\()(.*?)(?:\\))

const regex = /(?:\$\()(.*?)(?:\))/g;
const str = `\$(123=tr@e:123)124rt12\$(=ttre@tre)frg12<>\$(rez45)`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

PS:使用肯定的Lookarounds而不是非捕獲組將是有利的,但是JavaScript僅支持Lookaheads。

我試圖從字符串中提取$()內的數據。

您可以將.split()RegExp /\\)[^$]+|[$()]/以在")"處分割字符串,后跟一個或多個不是"$""$""("")"字符,請使用.filter()返回刪除了空字符串的數組

 var mystring = "$(123=tr@e:123)124rt12$(=ttre@tre)frg12<>$(rez45)"; var reg = /\\)[^$]+|[$()]/; var res = mystring.split(reg).filter(Boolean); console.log(res); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM