【问题标题】:Regex - Find from second occurrence till second last occurrence正则表达式 - 从第二次出现到倒数第二次查找
【发布时间】:2013-12-04 20:15:46
【问题描述】:

我正在尝试使用 Javascript 的 .match() 或 .replace() 函数匹配第一次和最后一次出现之间的所有内容。因此,我将使用正则表达式来查找我需要删除的内容。内容会因许多行和其他字符而有所不同,但这只是一个示例。

[quote=Person 1]
[quote=Person 2]
[quote=Person 3]
Person 3
[/quote]
Person 2
[/quote]
Person 1
[/quote]

我需要匹配并删除从第二次出现 [quote=Person 2] 到倒数第二次 [/quote]

的所有内容

话虽如此,它应该在最后输出:

[quote=Person 1]
Person 1
[/quote]

你可以像这样匹配引号标签

\[quote(.*?)\] 

和这样的结束引号标签

\[\/quote\]

【问题讨论】:

  • str.split('[quote=Person 2]').shift()+str.split('[/quote]').filter(function(n) {return n.trim().length}).pop()
  • JSfiddle,拜托。以此为例:jsfiddle.net/wQ4Fu
  • 你在跟我说话吗?如果是这样,字符串是不可变的 -> jsfiddle.net/wQ4Fu/3

标签: javascript jquery html regex


【解决方案1】:

给你(x 是上面的示例文本):

var newx = x.replace(/^(\[quote=(?:(?!\[quote=)[\s\S]*?))\[quote=[\s\S]+\[\/quote\]\s*([\s\S]+?\[\/quote\]\s*)$/g, "$1$2")

这会产生:

[quote=Person 1]
Person 1
[/quote]

请注意,x.replace() 不会更改 x 的内容——您必须执行 var newx = x.replace(...);x = x.replace(...) 之类的赋值来存储修改后的字符串。

【讨论】:

  • @LemvigKiggeren——它就像我写的那样工作。 .replace() 不做作业。因此,如果您执行x.replace(...),然后回显x,您将获得原始值。我已经调整了我的答案以澄清。
【解决方案2】:

使用此模式 (\[quote=([^\]]+)\])[\s\S]+(?=\s\2) 并替换为 $1 Demo

【讨论】:

    猜你喜欢
    • 2021-04-15
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 2021-01-06
    相关资源
    最近更新 更多