简体   繁体   English

Regex.Replace仅替换字符串的开头

[英]Regex.Replace only replaces start of string

I'm trying to replace a friendly url pattern with a html url notation but due to lack of regex experience I can't figure out why my regex only replaces the first occurence of my pattern: 我正在尝试用html url表示法替换友好的url模式,但是由于缺乏正则表达式的经验,我不知道为什么我的正则表达式仅替换了我的模式的第一次出现:

string text = "[Hotel Des Terrasses \http://flash-hotel.fr/] and [Du Phare \http://www.activehotels.com/hotel/]";
text = Regex.Replace(text, @"\[(.+)\s*\\(.+)\]", "<a href=\"$2\" target=\"_blank\">$1</a>");

How can i make the second pattern be replaced with the HTML markup too? 我如何也可以用HTML标记替换第二种模式?

Your regex treats the entire string as a single match. 您的正则表达式将整个字符串视为单个匹配项。 Try using (.+?) instead of (.+) (both instances). 尝试使用(.+?)代替(.+) (两个实例)。

As an aside note, you might want to consider potential abuse of this. 顺便提一句,您可能要考虑潜在的滥用。 You should probably perform: 您可能应该执行:

        StringBuilder sb = new StringBuilder();
        int pos = 0;

        Regex exp = new Regex(@"\[(.+?)\s*\\(.+?)\]");
        foreach (Match m in exp.Matches(text))
        {
            sb.Append(text, pos, m.Index - pos);
            pos = m.Index + m.Length;

            Uri tmp;
            if(Uri .TryCreate(m.Groups[2], UriKind.Absolute, out tmp))
            {
                sb.AppendFormat("<a href=\"{0}\" target=\"_blank\">{1}</a>",
                    System.Web.HttpUtility.HtmlAttributeEncode(tmp.AbsoluteUri),
                    System.Web.HttpUtility.HtmlEncode(m.Groups[1])
                    );
            }
        }
        sb.Append(text, pos, text.Length - pos);

Note: Not sure of the group indexes, I'd use named groups in the reg-ex. 注意:不确定组索引,我会在reg-ex中使用命名组。 Have you tried a regex tool like Expresso ? 您是否尝试过Expresso之类的正则表达式工具?

The regular expression takes the longest match, which in this case is the entire string, because your conditions are that it starts with a [ , ends with a ] and has at least one backslash somewhere in between. 正则表达式需要最长的匹配,在这种情况下,它是整个字符串,因为您的条件是它以[开头,以]结束,并且之间至少有一个反斜杠。 Re-specify the regular expression so as not to allow another ] inside the brackets, eg use [^\\]] instead of . 重新指定正则表达式,以免括号内包含另一个] ,例如,使用[^\\]]代替. (both occurrences). (两次出现)。

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

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