如何从正则表达式的结果中获取数组

时间:2022-10-10 21:18:03

I'm not able to get an array from the result of a regex match:

我无法从正则表达式匹配的结果中获取数组:

var txt = '[Eig2]=>100 [Eig1]=="test"';
var reg = '(\\[)((?:[a-z][a-z]+))(\\d+)(\\])';
var m = txt.match(new RegExp(reg, ["i"]));
if (m != null) {
    for (var i = 0; i < m.length; i++) {
        console.log(m[i]);
    }
} else {
    console.log("null");
}

What it returns:

它返回的内容:

[Eig2] 
[ 
Eig 
2 
]

What I want:

我想要的是:

[Eig2]
[Eig1]

May I have to do it without "new RegExp", but with "/([)((?:[a-z][a-z]+))(\d+)(])/g" it does not work...

我可以不用“新的RegExp”来做,但是用“/([)((?:[a-z] [a-z] +))(\ d +)(])/ g”它不起作用......

Some ideas?

Regards

2 个解决方案

#1


2  

First, I would simplify the expression:

首先,我会简化表达式:

var re = /\[([a-z]{2,}\d+)\]/ig;

I've added the /i for case insensitive matching and /g modifier to match multiple occurrences. Then you call it like this:

我添加了/ i用于不区分大小写的匹配和/ g修饰符以匹配多次出现。然后你这样称呼它:

> txt.match(re);
  ["[Eig2]", "[Eig1]"]

To extract the first memory capture:

提取第一个内存捕获:

var captures = [];

txt.replace(re, function($0, $1) {
    captures.push($1);
});

Granted, .replace() is being abused here

当然,.replace()在这里被滥用了

Then, evaluate captures:

然后,评估捕获:

> captures
  ["Eigh2", "Eigh1"]

Update

A somewhat friendlier way to build the array of memory captures:

一种更友好的方式来构建内存捕获数组:

var captures = [], match;

while ((match = re.exec(txt)) !== null) {
    captures.push(match[1]);
});

#2


2  

You should modify

你应该修改

var m = txt.match(new RegExp(reg, ["i"]));

to

var m = txt.match(new RegExp(reg, ["ig"]));

Add the g flag to your regular expression, which means you want to match all patterns in the string, instead of the first one and its subpatterns.

将g标志添加到正则表达式中,这意味着您要匹配字符串中的所有模式,而不是第一个模式及其子模式。

#1


2  

First, I would simplify the expression:

首先,我会简化表达式:

var re = /\[([a-z]{2,}\d+)\]/ig;

I've added the /i for case insensitive matching and /g modifier to match multiple occurrences. Then you call it like this:

我添加了/ i用于不区分大小写的匹配和/ g修饰符以匹配多次出现。然后你这样称呼它:

> txt.match(re);
  ["[Eig2]", "[Eig1]"]

To extract the first memory capture:

提取第一个内存捕获:

var captures = [];

txt.replace(re, function($0, $1) {
    captures.push($1);
});

Granted, .replace() is being abused here

当然,.replace()在这里被滥用了

Then, evaluate captures:

然后,评估捕获:

> captures
  ["Eigh2", "Eigh1"]

Update

A somewhat friendlier way to build the array of memory captures:

一种更友好的方式来构建内存捕获数组:

var captures = [], match;

while ((match = re.exec(txt)) !== null) {
    captures.push(match[1]);
});

#2


2  

You should modify

你应该修改

var m = txt.match(new RegExp(reg, ["i"]));

to

var m = txt.match(new RegExp(reg, ["ig"]));

Add the g flag to your regular expression, which means you want to match all patterns in the string, instead of the first one and its subpatterns.

将g标志添加到正则表达式中,这意味着您要匹配字符串中的所有模式,而不是第一个模式及其子模式。