简体   繁体   中英

Regular expression to match specific words + content inside brackets

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".

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:

new Regex(@"\[flash:(.+?)\]");

Try this:

new Regex(@"\[flash:([^\]]+)\]");
\[flash:          # prefix
  (               # capture group
      [^\]]+      # one or more characters except ]
  )               #
\]                # suffix

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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