Javascript Regex匹配最后一次出现字符串后的所有内容 [英] Javascript Regex match everything after last occurrence of string

查看:32
本文介绍了Javascript Regex匹配最后一次出现字符串后的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to match everything after (but not including!) the last occurrence of a string in 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]"之后匹配所有内容?不知道这是否是最好的解决方案,但这是我一直在尝试的.

I'm looking to match everything after the last quote block. So I was trying to match everything after the last occurrence of "quote]" ? Idk if this is the best solution but its what i've been trying.

老实说,我很讨厌这个 Regex 的东西..这是我一直在尝试的结果..

I'll be honest, i suck at this Regex stuff.. here is what i've been trying with the results..

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

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

I have made a JSfiddle for anyone to have a play with here:

https://jsfiddle.net/au4bpk0e/

推荐答案

一种选择是匹配所有内容,直到最后一个 [/quote],然后获取其后的任何内容.(示例)

One option would be to match everything up until the last [/quote], and then get anything following it. (example)

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

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

This works since .* is inherently greedy, and it will match every up until the last \[\/quote\].

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

Based on the string you provided, this would be the first capturing group match:

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

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

But since your string contains new lines, and . doesn't match newlines, you could use [\s\S] in place of . in order to match anything.

更新示例

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

<小时>

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

更新示例

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

<小时>

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


Alternatively, you could also use .split() and then get the last value in the array:

更新示例

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

这篇关于Javascript Regex匹配最后一次出现字符串后的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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