【问题标题】:Replace string using regular expression at specific position dynamically set在动态设置的特定位置使用正则表达式替换字符串
【发布时间】:2014-08-14 15:27:22
【问题描述】:

我想使用正则表达式从匹配的模式字符串中替换一个字符串。

这是我的字符串:

"this is just a simple text. this is just a simple text. this is just a simple text. this is just a simple text. How are you man today. I Have been working on this."

现在,我有一种情况,我想用"hello" 替换"just a simple",但在字符串的第三次出现中。所以任何人都可以指导我完成这个我会非常有帮助。 但转折来了。上面的字符串是动态的。用户可以修改或改变文本。

那么我该如何检查,如果用户在字符串的开头或第三次出现更改我的字符串替换位置之前添加"this is just a simple text" 一次或多次?

对不起,如果我不清楚;但任何指导或帮助或任何其他方法都会有所帮助。

【问题讨论】:

  • 如果可能的话,可以澄清一下“那么我该如何检查,如果用户在开始或第三次出现字符串之前添加“这只是一个简单的文本”一次或多次改变我的字符串替换位置?" ?如果将“这只是一个简单的文本”添加到字符串中,“字符串替换位置”会是什么?谢谢

标签: javascript regex


【解决方案1】:

你可以使用这个正则表达式:

(?:.*?(just a simple)){3}

Working demo

【讨论】:

  • 你能在 JavaScript 中做到这一点吗?
  • 我知道你没有真正测试...尝试用你的正则表达式编写替换函数...
【解决方案2】:

您可以将replace 与动态构建的正则表达式和一个回调一起使用,您可以在其中计算搜索到的模式的出现次数:

var s = "this is just a simple text. this is just a simple text. this is just a simple text. this is just a simple text. How are you man today. I Have been working on this.",
    pattern = "just a simple",
    escapedPattern = pattern.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'),
    i=0;
s = s.replace(new RegExp(escapedPattern,'g'), function(t){ return ++i===3 ? "hello" : t });

请注意,我使用this related QA 来转义模式中的任何“特殊”字符。

【讨论】:

  • 好极了,一个 LAMBDA 回调表达式!
【解决方案3】:

试试

$(selector)
.data("r", ["simple text", 3, "hello"])
.text(function (i, o) {
    var r = $(this).data("r");
    return o.replace(new RegExp(r[0], "g"), function (m) {
        ++i;
        return (i === r[1]) ? r[2] : m
    })
}).data("r", []);

jsfiddle http://jsfiddle.net/guest271314/2fm91qox/

Find and replace nth occurrence of [bracketed] expression in string

Replacing the nth instance of a regex match in Javascript

JavaScript: how can I replace only Nth match in the string?

【讨论】:

    猜你喜欢
    • 2013-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 2021-12-19
    • 2013-05-11
    • 2021-11-20
    • 1970-01-01
    相关资源
    最近更新 更多