匹配特定单词的正则表达式 +括号内的内容
我正在创建一个帖子系统,我将在其中使用 [image:http://anything/anyimage.jpg] 或 [silverlight:http://anothersite/ilovesilverlight.xap] 等标记外部图像、Flash、SL 等。我将在找到链接后呈现 HTML 的对象标签。我被正则表达式困住了,我对正则表达式很陌生,所以请在回复时保持建设性,这有什么问题:
if (text.Contains("[flash:"))
{
rgx = new Regex(@"\[flash:(.^\])\]");
text = rgx.Replace(text, (m =>
{
string val = m.Groups[1].Value;
FlashRenderer ir = new FlashRenderer(val);
return ir.Render();
}));
}
忘记 FlashRenderer
及其返回的内容,我的问题是匹配。 我进入 if 块,但找不到任何与正则表达式匹配的实例,尽管我有。我可以在一篇文章中包含多个外部对象,因此我要做的是否定匹配中的 ]
字符。如果我不否定 ]
,如果我只有一个对象并且任何地方都没有其他 ]
字符,那么没有问题,但如果我有更多 ] 然后一切都会变得混乱,因为第一个正则表达式与整个帖子中最后一次出现的
]
匹配,并将整个帖子的其余部分作为假定的“URL”返回。
I'm creating a post system, where I will tag external images, Flash, SL etc. with [image:http://anything/anyimage.jpg] or [silverlight:http://anothersite/ilovesilverlight.xap] etc. I'll be rendering the object tags for HTML upon finding the links. I'm stuck with regex, I am quite new to regex so please be constructive while replying, what is wrong with this:
if (text.Contains("[flash:"))
{
rgx = new Regex(@"\[flash:(.^\])\]");
text = rgx.Replace(text, (m =>
{
string val = m.Groups[1].Value;
FlashRenderer ir = new FlashRenderer(val);
return ir.Render();
}));
}
Forget about the FlashRenderer
and what it returns, my problem is with matching.
I get into the if block, but cannot find any instances that match the regex, although I have. I can have multiple external objects in one post, so what I'm trying to do is to negate the ]
character in the match. If I don't negate ]
, there is no problem if I have only one object and no other ]
characters anywhere, but if I have more ]
's then everything gets messed up as the first regex matches the last occurance of ]
on the whole post, and returning the rest of the whole post as the supposed "URL".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用所谓的“非贪婪量词”,这意味着它在仍然匹配的同时会吃掉尽可能多的字符,而默认(贪婪)量词在仍然匹配的同时会吃掉尽可能多的字符。您可以通过在量词(如
*
或+
)后面放置?
使其成为非贪婪的:You can use what's called a "non-greedy quantifier", which just means that it eats as few characters as it can while still matching, while the default (greedy) quantifiers eat as many characters as they can while still matching. You make a quantifier (like
*
or+
) non-greedy by putting a?
after it:试试这个:
Try this: