通过Javascript中的匹配替换

时间:2019-06-08 18:01:25

标签: javascript regex replace regex-lookarounds regex-group

我需要匹配数字后跟一个单位,并使用Javascript将其替换为数字+下划线+单位。

我想出了这段代码,但并没有产生我想要获得的结果。

var x = myFunction("I have 3 billion dollars");

function myFunction(text) {
return  text.replace(/(\d+\.?(?:\d{1,2})?) (\bmillion\b|\bbillion\b|\bbillion\b|\bmillions\b|\bbillions\b|\btrillion\b|\btrillions\b|\bmeter\b|\bmeters\b|\bmile\b|\bmiles\b|\%)/gi, function (match) {
          return "<span class='highlighted'>" + match[1] + "_" + match[2] + "</span>";
    });
 }

上面的代码应返回“我有3十亿美元”(但就替换而言,它返回_b)。因为我是Java的新手,所以任何建议都将不胜感激。

修改 已经有许多有用的提示!这里还有一些插补示例:

the street is 4.5 miles long
the budget was 430.000 dollars

3 个答案:

答案 0 :(得分:2)

为您提供更简单清晰的示例

let regex = /\d+ (million|billion|millions|billions|trillion|trillions|meter|meters|mile|miles)/g

let match = "I have 3 billion dollars".match(regex)
let replace = match.map(x => x.split(" ").join("_"))

console.log(replace)

答案 1 :(得分:1)

match不是数组,而是字符串。您可以split ' '加入_

加入

var x = myFunction("I have 3 billion dollars");

function myFunction(text) {
return  text.replace(/(\d+\.?(?:\d{1,2})?) (\bmillion\b|\bbillion\b|\bbillion\b|\bmillions\b|\bbillions\b|\btrillion\b|\btrillions\b|\bmeter\b|\bmeters\b|\bmile\b|\bmiles\b|\%)/gi, function (match) {
          console.log(match)
          return "<span class='highlighted'>" +match.split(' ').join('_')+ "</span>";
    });
 }
console.log(x)

答案 2 :(得分:1)

如果可以,我们可以在您的原始表达式中使用str.replace

const regex = /(\d+\.?(?:\d{1,2})?) (\bmillion\b|\bbillion\b|\bbillion\b|\bmillions\b|\bbillions\b|\btrillion\b|\btrillions\b|\bmeter\b|\bmeters\b|\bmile\b|\bmiles\b|\%)/gm;
const str = `3 billion
3 million`;
const subst = `<span class='highlighted'>" $1_$2 "</span>`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

此外,我们可以稍微简化一下表达式:

(\d+\.?(?:\d{1,2})?) (\bmillions?\b|\bbillions?\b|\btrillions?\b|\bmeters?\b|\bmiles?\b|\%)

const regex = /(\d+\.?(?:\d{1,2})?) (\bmillions?\b|\bbillions?\b|\btrillions?\b|\bmeters?\b|\bmiles?\b|\%)/gm;
const str = `3 billion
3 million
3 %
2 meters`;
const subst = `<span class='highlighted'>" $1_$2 "</span>`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log(result);

Demo

RegEx

如果不需要此表达式,并且希望对其进行修改,请访问regex101.com上的此链接。

RegEx电路

jex.im可视化正则表达式:

enter image description here