我有一个代码,该代码使用正则表达式中的匹配组来操纵字符串。
something = mystring.replace(someRegexObject, '$1' + someotherstring);
此代码在大多数情况下正常工作,但是当someotherstring
具有数字值时,我会遇到一个问题...然后将其与$ 1串联成组匹配。
我是否有一种简单的方法可以逃脱someotherstring
的内容将其与匹配组分开?
问题解释了
问题不是最明确的,但我认为我理解您的问题。
在JavaScript中使用REGEX,实际上,您可以使用$10
作为捕获组1的替代品,仅在 - 仅当 - 时才少于可用的10
组。有关此的示例,请参见下面的摘要。
const regex = /(w+)/g;
const str = `something`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, '$10');
console.log('Substitution result: ', result);
不幸的是,我相信您的正则捕获比X
多(如果您查看上面的示例,则10
)。看到它在下面的摘要中返回不正确的值。
const regex = /(w+)((((((((()))))))))/g;
const str = `something`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, '$10');
console.log('Substitution result: ', result);
解决方案
为了解决此问题,您必须更改JavaScript代码以在替换字符串的位置实现一个函数,如以下摘要所示。
const regex = /(w+)((((((((()))))))))/g;
const str = `something`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, function(a, b) {
return b+'0';
});
console.log('Substitution result: ', result);