【问题标题】:Escaping numerals in string.replace在 string.replace 中转义数字
【发布时间】:2017-09-27 20:29:05
【问题描述】:

我有一段代码使用正则表达式中的匹配组来操作字符串。

something = mystring.replace(someRegexObject, '$1' + someotherstring);

这段代码在大多数情况下都可以正常工作,但是当someotherstring 有一个数值时我会遇到问题......然后它会与 $1 连接起来,搞乱组匹配。

我有没有一种简单的方法可以将someotherstring 的内容从匹配组中分离出来?

【问题讨论】:

  • 提供正则表达式、一些导致问题的示例字符串和一些有效的字符串,以便我们为您提供帮助。以目前的数据,除了推测,我们无能为力。
  • 真的需要知道someRegexObjectsomeotherstring,还有mystring,因为你的问题是这样的:“有时候我用A然后不是B的时候涉及数字。"
  • 你确定这个问题出在 JS 正则表达式上吗?它通常可以毫无问题地处理。 @ctwheels ${1} 表示法在 PHP 和 .NET 中有效,在 JS 正则表达式中无效。
  • @ctwheels 对,it is lying a lot。 Regex101 从来都不是正则表达式是否有效的证明
  • @WiktorStribiżew 你是对的,我找到了一个不同的修复程序并发布了它。我还删除了我以前的 cmets,因为它们对这个问题不正确。

标签: javascript regex


【解决方案1】:

问题说明

这个问题不是最清楚的,但我想我理解你的问题。

在 JavaScript 中使用正则表达式,事实上,当且仅当可用的组少于 10 时,您可以使用 $10 作为捕获组 1 的替代品。有关此示例,请参见下面的 sn-p。

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);

不幸的是,我相信你有一个正则表达式,它捕获的不仅仅是X10,如果你正在看上面的例子)。看到它在下面的 sn-p 中返回了一个不正确的值。

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 代码以实现一个函数来代替替换字符串,如下面的 sn-p 所示。

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);

【讨论】:

    猜你喜欢
    • 2016-10-19
    • 1970-01-01
    • 2011-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 2019-02-24
    • 1970-01-01
    相关资源
    最近更新 更多