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

JavaScript using a variable with .match Regex Expression

我对正则表达式很陌生,但我想在我的比赛中使用一个变量。

所以我有一个字符串 "Total: 8" 我正在尝试获取号码数量,168。

所以我有这个:

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

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

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

我也是

 var stringToSearch = 'Total: $';

然后

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

我做了一个控制台日志:

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

我得到:

l: 8 || Total: $

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

你的正则表达式对 return "120"!

起作用真是太幸运了

[^Total: $]*$ 告诉正则表达式解析器匹配任何 other 除了括号 [..] ('T','o','t','a','l',' ', or '$'), 尽可能多次直到行尾 ($ 在这种情况下不是文字 '$' 字符)。那匹配的是什么呢?唯一落在字符 class 之外的字符:“1”、“2”、“0”。

您试图做的是在文字字符串 'Total: $':

之后捕获匹配的数字
var totalCost = 'Total: 8',
    matches = totalCost.match(/^Total: $([\d\.]*)/),
    totalCostNum = matches ? parseFloat(matches[1]) : 0;

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

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

看起来像你 can't interpolate into a JavaScript regex/[^stringToSearch]*$/ 将匹配任何以非文字字符串 "stringToSearch" 中的字符结尾的子字符串。如果要模块化,可以使用RegExp构造函数:

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

听起来您想将 regex 变成一个可用于不同输入的变量。尝试这样的事情:

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

你的正则表达式的逻辑也有一些问题,我在我的例子中已经改变了。它与您预期的不匹配。