简体   繁体   English

BBCode的JavaScript RegExp帮助

[英]JavaScript RegExp help for BBCode

I have this RegExp expression I found couple weeks ago 我有几个星期前发现的这个RegExp表达式

/([\r\n])|(?:\[([a-z\*]{1,16})(?:=([^\x00-\x1F"'\(\)<>\[\]]{1,256}))?\])|(?:\[\/([a-z]{1,16})\])/ig

And it's working to find the BBCode tags such as [url] and [code] . 它正在努力寻找BBCode标签,如[url][code]

However if I try [url="http://www.google.com"] it won't match. 但是,如果我尝试[url="http://www.google.com"] ,则无法匹配。 I'm not very good at RegExp and I can't figure out how to still be valid but the ="http://www.google.com" be optional. 我不是很擅长RegExp而且我无法弄清楚如何仍然有效,但="http://www.google.com"是可选的。

This also fails for [color="red"] but figure it is the same issue the url tag is having. 对于[color="red"]这也是失败的,但是这与url标签所具有的问题相同。

This part: [^\\x00-\\x1F"'\\(\\)<>\\[\\]] says that after the = there must not be a ". 这部分: [^\\x00-\\x1F"'\\(\\)<>\\[\\]]表示在=之后一定不能有”。 That means your regexp matches [url=http://stackoverflow.com] . 这意味着你的正则表达式匹配[url=http://stackoverflow.com] If you want to have quotes you can simply put them around your capturing group: 如果你想有引号,你可以简单地将它们放在捕获组周围:

/([\r\n])|(?:\[([a-z\*]{1,16})(?:="([^\x00-\x1F"'\(\)<>\[\]]{1,256})")?\])|(?:\[\/([a-z]{1,16})\])/gi

I think you would benefit from explicitly enumerating all the tags you want to match, since it should allow matching the closing tag more specifically. 我认为您可以从显式枚举您想要匹配的所有标记中受益,因为它应该允许更具体地匹配结束标记。

Here's a sample code : 这是一个示例代码

var tags = [ 'url', 'code', 'b' ]; // add more tags

var regParts = tags.map(function (tag) {
    return '(\\[' + tag + '(?:="[^"]*")?\\](?=.*?\\[\\/' + tag + '\\]))';
});

var re = new RegExp(regParts.join('|'), 'g');

You might notice that the regular expression is composed from a set of smaller ones, each representing a single tag with a possible attribute ( (?:="[^"]*")? , see explanation below) of variable length, like [url="google.com"] , and separated with the alternation operator | . 您可能会注意到正则表达式由一组较小的表达式组成,每个较小的一个表示具有可变长度的可能属性的单个标记( (?:="[^"]*")? ,见下面的解释),如[url="google.com"] ,并用交替运算符|分隔。

(="[^"]*")? means an = symbol, then a double quote, followed by any symbol other than double quote ( [^"] ) in any quantity, ie 0 or more, ( * ), followed by a closing quote. (="[^"]*")?表示=符号,然后是双引号,后跟任何数量的双引号( [^"]以外的任何符号,即0或更多,( * ),后跟收尾报价。 The final ? 决赛? means that the whole group may not be present at all. 意味着整个群体可能根本不存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM