0

I have an html string to work with as follows:

string html = new MvcHtmlString(item.html.ToString()).ToHtmlString();

There are two different types of text I need to match although very similar. I need the initial ^^ removed and the closing |^^ removed. Then if there are multiple clients I need the ^ separating clients changed to a comma(,).

^^Client One- This text is pretty meaningless for this task, but it will exist in the real document.|^^

^^Client One^Client Two^Client Three- This text is pretty meaningless for this task, but it will exist in the real document.|^^

I need to be able to match each client and make it bold.

Client One- This text is pretty meaningless for this task, but it will exist in the real document.

Client One, Client Two, Client Three- This text is pretty meaningless for this task, but it will exist in the real document.

A nice stack over flow user provided the following but I could not get it to work or find any matches when I tested it on an online regex tester.

const string pattern = @"\^\^(?<clients>[^-]+)(?<text>-.*)\|\^\^";

    var result = Regex.Replace(html, pattern,
                                m =>
                                {
                                    var clientlist = m.Groups["clients"].Value;
                                    var newClients = string.Join(",", clientlist.Split('^').Select(s => string.Format("<strong>{0}</strong>", s)));

                                    return newClients + m.Groups["text"];
                                });

I am very new to regex so any help is appreciated.

4

1 回答 1

2

我是 C# 的新手,如果我犯了菜鸟的错误,请原谅我 :)

const string pattern = @"\^\^([^-]+)(-[^|]+)\|\^\^";

var temp = Regex.Replace(html, pattern, "<strong>$1</strong>$2");
var result = Regex.Replace(temp, @"\^", "</strong>, <strong>");

$1即使 MSDN 对使用该语法来引用子组含糊其辞,我仍在使用。

编辑:如果后面的文本可能-包含 a^你可以这样做:

var result = Regex.Replace(temp, @"\^(?=.*-)", "</strong>, <strong>");
于 2013-08-30T17:11:03.493 回答