制作一个聪明的正则表达式 [英] Making a smart regex

查看:62
本文介绍了制作一个聪明的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用

JavaScript编写一个将BBcode解析为HTML的正则表达式。使用字符串类

replace()运算符和regex'的所有内容都很顺利,直到我到达list标签。

实现list标签本身相当容易。什么不是

试图处理列表项。出于某种原因,在BBcode中,他们

并没有为列表项定义结束标记。我猜他们

设计它与旧的HTML 3.2一样,你可以使用以下方式制作一个清单




< ul>

< li> item 1

< li> item2

< / ul>


但是,我需要使这个符合XHTML,所以我需要添加

< / li>标签混合。不幸的是,找到

的唯一方法是找到下一个[*](< li>)标签或打开的列表(在这种情况下

嵌套列表)或关闭列表标签。我试图得到一个规则,

处理列表项工作,但它只匹配

任何列表中的第一项。以下是代码行:


bbcode =

bbcode.replace(/ \ [list(\ = 1 | \ = a |) \] \ [\ * \(\ [\ * \](*。?)(*。?)| \ [list\] | \ [\ / list\ ])/ g,

''[list $ 1] $ 2< li> $ 3< / li> $ 4'');


首先,我检查以确保列表项位于列表中。然后,

我匹配[*]标签找到项目的开头,然后我匹配

下一个[*],

  • ,或
以确定项目的结尾。

这成功地防止了列表之外的列表项目被制成<李>元素,但仅匹配

列表中的第一个列表项。有没有办法让这个匹配所有出现这个

模式没有循环语句,直到模式不能再找到


非常感谢你的帮助


Chris Lieb

解决方案

1 ]

2';李>

3'; /锂>

I am trying to write a regex that will parse BBcode into HTML using
JavaScript. Everything was going smoothly using the string class
replace() operator with regex''s until I got to the list tag.
Implementing the list tag itself was fairly easy. What was not was
trying to handle the list items. For some reason, in BBcode, they
didn''t bother defining an end tag for a list item. I guess that they
designed it with bad old HTML 3.2 in mind where you could make a list
by using:

<ul>
<li>item 1
<li>item2
</ul>

However, I need to make this XHTML compliant, so I needed to add the
</li> tag into the mix. Unfortunately, the only way to find where to
put it is to find the next[*] (<li>) tag or an open list (in the case
of nested lists) or close list tag. I was trying to get a rule that
handles the list items to work, but it only matches the first item in
any list. Here is the line of code:

bbcode =
bbcode.replace(/\[list(\=1|\=a|)\](.*?)\[\*\](.*?)(\[\*\]|\[list\]|\[\/list\])/g,
''[list$1]$2<li>$3</li>$4'');

First, I check to make sure that the list item is inside a list. Then,
I match the[*] tag to find the start of the item, then I match either
the next[*],

  • , or
to determine the end of the item.
This successfully prevents a list item outside of a list from being
made into a <li> element, but only matches the first list item in a
list. Is there any way to make this match all occurances of this
pattern without looping over the statement until the pattern can no
longer be found?

Your help is much appreciated

Chris Lieb

解决方案

1]


2<li>


3</li>


这篇关于制作一个聪明的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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