【问题标题】:Javascript Regex match everything after last occurrence of stringJavascript Regex 匹配最后一次出现字符串后的所有内容
【发布时间】:2016-01-09 20:41:50
【问题描述】:

我试图匹配(但不包括!)JavaScript 中最后一次出现的字符串之后的所有内容。

例如,搜索是:

[quote="user1"]this is the first quote[/quote]\n[quote="user2"]this is the 2nd quote and some url https://www.google.com/[/quote]\nThis is all the text I\'m wirting about myself.\n\nLook at me ma. Javascript.

编辑:我希望匹配最后一个引用块之后的所有内容。所以我试图在最后一次出现 "quote]" 之后匹配所有内容? Idk 如果这是最好的解决方案,但它是我一直在尝试的。

说实话,我很讨厌这个正则表达式的东西。这是我一直在尝试的结果。

regex = /(quote\].+)(.*)/ig; // Returns null 
regex = /.+((quote\]).+)$/ig // Returns null  
regex = /( .* (quote\]) .*)$/ig  // Returns null   

我制作了一个 JSfiddle 供任何人在这里玩:

https://jsfiddle.net/au4bpk0e/

【问题讨论】:

  • 我不明白你想匹配什么。 what 字符串在您的字符串中的最后一次出现?
  • 对不起,我正在尝试匹配最后一个引号之后的所有内容...
  • 那为什么要使用正则表达式呢?使用带有 lastIndexOf 的子字符串。

标签: javascript regex


【解决方案1】:

一种选择是将所有内容匹配到最后一个[/quote],然后在它后面获取任何内容。 (example)

/.*\[\/quote\](.*)$/i

这是有效的,因为.* 本质上是贪婪的,它会匹配每一个直到最后一个\[\/quote\]。

根据您提供的字符串,这将是第一个捕获组匹配:

\nThis is all the text I\'m wirting about myself.\n\nLook at me ma. Javascript.

但是由于您的字符串包含换行符,并且. 不匹配换行符,您可以使用[\s\S] 代替. 来匹配任何内容。

Updated Example

/[\s\S]*\[\/quote\]([\s\S]*)$/i

您也可以避免使用正则表达式并使用.lastIndexOf() method 和.slice():

Updated Example

var match = '[\/quote]';
var textAfterLastQuote = str.slice(str.lastIndexOf(match) + match.length);
document.getElementById('res').innerHTML = "Results: " + textAfterLastQuote;

或者,您也可以使用.split(),然后获取数组中的最后一个值:

Updated Example

var textAfterLastQuote = str.split('[\/quote]').pop();
document.getElementById('res').innerHTML = "Results: " + textAfterLastQuote;

【讨论】:

  • 您先生..是英雄!优秀作品。非常感激。希望用户能从谷歌上找到这个标题,寻找类似的东西,也感谢你的回答。
猜你喜欢
  • 2017-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-28
相关资源
最近更新 更多