在Javascript中替换正则表达式匹配的第n个实例 [英] Replacing the nth instance of a regex match in Javascript

查看:157
本文介绍了在Javascript中替换正则表达式匹配的第n个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个正则表达式函数,该函数将识别并替换字符串中匹配的单个实例,而不会影响其他实例。例如,我有这个字符串:

I'm trying to write a regex function that will identify and replace a single instance of a match within a string without affecting the other instances. For example, I have this string:

12||34||56

我想用&符替换第二组管道来获取此字符串:

I want to replace the second set of pipes with ampersands to get this string:

12||34&&56

正则表达式函数需要能够处理x数量的管道并允许我替换第n组管道,所以我可以使用相同的功能来进行这些替换:

The regex function needs to be able to handle x amount of pipes and allow me to replace the nth set of pipes, so I could use the same function to make these replacements:

23||45||45||56||67 -> 23&&45||45||56||67

23||34||98||87 -> 23||34||98&&87

我知道我可以拆分/替换/在管道上连接字符串,我也知道我可以匹配 / \ | \ | / 并迭代生成的数组,但我很感兴趣知道是否可以写一个可以做到这一点的表达式。请注意,这将适用于Javascript,因此可以使用 eval()在运行时生成正则表达式,但是不可能使用任何特定于Perl的正则表达式指令。

I know that I could just split/replace/concat the string at the pipes, and I also know that I can match on /\|\|/ and iterate through the resulting array, but I'm interested to know if it's possible to write a single expression that can do this. Note that this would be for Javascript, so it's possible to generate a regex at runtime using eval(), but it's not possible to use any Perl-specific regex instructions.

推荐答案

这里有用的东西:

"23||45||45||56||67".replace(/^((?:[0-9]+\|\|){n})([0-9]+)\|\|/,"$1$2&&")

其中n是小于第n个管道的那个(当然,如果n = 0,你不需要第一个子表达式)

where n is the one less than the nth pipe, (of course you don't need that first subexpression if n = 0)

如果你想要一个函数来做这个:

And if you'd like a function to do this:

function pipe_replace(str,n) {
   var RE = new RegExp("^((?:[0-9]+\\|\\|){" + (n-1) + "})([0-9]+)\|\|");
   return str.replace(RE,"$1$2&&");
}

这篇关于在Javascript中替换正则表达式匹配的第n个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆