regex开始和结束匹配

regex start and end matching

本文关键字:结束 开始 regex      更新时间:2023-09-26

所以我在正则表达式中遇到了一点麻烦,我有一个分别匹配开头和结尾的表达式。当我试图在同一个表达式中匹配开头和结尾时,就会出现问题,我不明白为什么会出现问题。我甚至尝试过计算开始和结束标签之间的内容,但仍然没有成功。

Works: /^([ ])?'[('/?)gaiarch(=[^"]*)?]([ ])?/ig
Works: /([ ])?'[('/?)gaiarch(=[^"]*)?]([ ])?$/ig
Doesn't work: /^([ ])?'[('/?)gaiarch(=[^"]*)?]([ ])?$/ig

我想让它匹配:

[gaiarch=slider]
[img url="http://i1251.photobucket.com/albums/hh543/Knight-Yoshi/trade_c.png" text="Trading Image" goto="http://www.gaiaonline.com/gaia/bank.php?mode=trade&uid=15388423"],[img url="http://i1251.photobucket.com/albums/hh543/Knight-Yoshi/friend_c.png" text="Friends Image" goto="http://www.gaiaonline.com/friends/add/15388423"][/gaiarch]
 [gaiarch=slider][img url="http://i1251.photobucket.com/albums/hh543/Knight-Yoshi/gaiaonline/thread/post/dark-center_bottom_zps419960f4.gif" text="bottom bar"]
[img url="http://i1251.photobucket.com/albums/hh543/Knight-Yoshi/gaiaonline/thread/post/star-say_right_zpsdc3769f3.png" goto="http://www.gaiaonline.com/"][/gaiarch] 

问题是您没有匹配打开和关闭标记之间的内容;表达式要求字符串中只有一个开始或结束标记。

要匹配打开和关闭标签之间的内容,您需要这样的东西:

/'[gaiarch(?:=([^']]+))?'](.*?)'['/gaiarch']/ig

要使此表达式工作,可以使用RegExp.exec():

var re = /'[gaiarch(?:=([^']]+))?'](.*?)'['/gaiarch']/ig;
while ((match = re.exec(str)) !== null) {
    console.log(match[1]) // "slider"
    console.log(match[2]) // "[img url=...]"
}