使用带有.match Regex表达式的变量的JavaScript

JavaScript using a variable with .match Regex Expression

本文关键字:表达式 变量 JavaScript Regex match      更新时间:2023-09-26

我对regex很陌生,但我正在尝试在匹配中使用一个变量。

所以我有一个字符串,它是"总计:$168"我想知道168这个数字。

所以我有这个:

totalCost = totalCost.match(/[^Total: $]*$/);

当我回应的时候,我得到了168。这是有效的,这是我想要的。

但现在我想更进一步,想让"Total:$"成为一个变量,这样我就可以轻松地设置它并使其模块化。

所以我做了

 var stringToSearch = 'Total: $';

然后做

 totalCost = totalCost.match(/[^stringToSearch]*$/);

我做了一个控制台日志:

 console.log(totalCost+" || "+stringToSearch );

我得到:

l: $168 || Total: $

为什么当我创建这个变量时,它的行为都很奇怪?

您的正则表达式能够返回"120"真是太幸运了!

[^Total: $]*$告诉regex解析器匹配除了括号[之间的字符之外的任何。。]('T'、'o'、'T'、'a'、'l'、''或'$'),尽可能多次,直到行尾(在这种情况下,$不是文字'$'字符)。那么它匹配什么呢?唯一位于字符类中的字符之外的字符:"1"、"2"、"0"。

您试图做的是在文字字符串"Total:$"之后捕获匹配的数字:

var totalCost = 'Total: $168',
    matches = totalCost.match(/^Total: '$(['d'.]*)/),
    totalCostNum = matches ? parseFloat(matches[1]) : 0;

要生成该变量,您需要首先转义您的变量,以便可以从字面上匹配文本,然后使用new RegExp构建正则表达式:

var totalCost = 'Total: $168',
    stringToMatch = 'Total: $',
    stringToMatchEscaped = stringToMatch.replace(/[-'/''^$*+?.()|[']{}]/g, '''$&'),
    stringToMatchRegEx = new RegExp(stringToMatchEscaped + /(['d'.]*)/.source),
    matches = totalCost.match(stringToMatchRegEx),
    totalCostNum = matches ? parseFloat(matches[1]) : 0;

看起来您无法插入JavaScript正则表达式。CCD_ 7将匹配以文字字符串"stringToSearch"中的字符以外的字符结尾的任何子字符串。如果你想模块化,你可以使用RegExp构造函数:

totalCost = totalCost.match(new RegExp("[^" + stringToSearch + "]*$"));

听起来你想把regex变成一个可以在不同输入中使用的变量。试试这样的东西:

var regex = /^Total: '$('d+)/;
regex.exec('Total: $168');
// [ 'Total: $168', '168', index: 0, input: 'Total: $168' ]
regex.exec('Total: $123');
// [ 'Total: $123', '123', index: 0, input: 'Total: $123' ]

正则表达式的逻辑也有一些问题,我在示例中对此进行了更改。它并不像你所期望的那样匹配。