我对正则表达式很陌生,但我尝试在匹配中使用变量。
所以我有一个字符串是"总计:$ 168" 我试图获得数量,168。
所以我有这个:
totalCost = totalCost.match(/[^Total: $]*$/);
当我回应时,我得到168。 这是有效的,这就是我想要的。
但现在我想更进一步,想要制作"总计:$"一个变量,所以我可以很容易地设置它并使其模块化。
所以我做了
var stringToSearch = 'Total: $';
然后做了
totalCost = totalCost.match(/[^stringToSearch]*$/);
我做了一个控制台日志:
console.log(totalCost+" || "+stringToSearch );
我得到了:
l: $168 || Total: $
为什么当我制作这个变量时,它表现得很奇怪?
答案 0 :(得分:2)
纯正的运气,你的正则表达式回归"120"
!
[^Total: $]*$
告诉正则表达式解析器匹配任何其他而不是括号[
之间的字符]
(' T' ,'''''' l'''或' ; $'),尽可能多次直到行尾($
不是文字' $'字符)。那它匹配的是什么?唯一不属于角色类别的人物:' 1',' 2'' 0'。
你要做的是在文字字符串之后捕获匹配的数字'总计:$':
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;
答案 1 :(得分:1)
看起来像你can't interpolate into a JavaScript regex。 /[^stringToSearch]*$/
将匹配任何以字符串"stringToSearch"
中的字符以外的字符结尾的子字符串。如果您想要模块化,可以使用RegExp
构造函数:
totalCost = totalCost.match(new RegExp("[^" + stringToSearch + "]*$"));
答案 2 :(得分:1)
听起来您希望将正则表达式变成可以在不同输入上使用的变量。尝试这样的事情:
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' ]
你的正则表达式的逻辑也存在一些问题,我在我的例子中已经改变了。它没有像你期望的那样匹配。