Question

In C#, Windows Form, how would I accomplish this:


07:55 Header Text:  This is the data<br/>07:55 Header Text:  This is the data<br/>07:55 Header Text:  This is the data<br/>

So, as you can see, i have a return string, that can be rather long, but i want to be able to format the data to be something like this:


<b><font color="Red">07:55 Header Text</font></b>:  This is the data<br/><b><font color="Red">07:55 Header Text</font></b>:  This is the data<br/><b><font color="Red">07:55 Header Text</font></b>:  This is the data<br/>

As you can see, i essentially want to prepend <b><font color="Red"> to the front of the header text & time, and append </font></b> right before the : section.

So yeah lol i'm kinda lost.

I have messed around with .Replace() and Regex patterns, but not with much success. I dont really want to REPLACE text, just append/pre-pend at certain positions.

Is there an easy way to do this?

Note: the [] tags are actually <> tags, but i can't use them here lol

Was it helpful?

Solution

Just because you're using RegEx doesn't mean you have to replace text.

The following regular expression:

(\d+:\d+.*?:)(\s.*?\[br/\])

Has two 'capturing groups.' You can then replace the entire text string with the following:

[b][font color="Red"]\1[/font][/b]\2

Which should result in the following output:

[b][font color="Red"]07:55 Header Text:[/font][/b] This is the data[br/]
[b][font color="Red"]07:55 Header Text:[/font][/b] This is the data[br/]
[b][font color="Red"]07:55 Header Text:[/font][/b] This is the data[br/]

Edit: Here's some C# code which demonstrates the above:

var fixMe = @"07:55 Header Text: This is the data[br/]07:55 Header Text: This is the data[br/]07:55 Header Text: This is the data[br/]";
var regex = new Regex(@"(\d+:\d+.*?:)(\s.*?\[br/\])");
var matches = regex.Matches(fixMe);

var prepend = @"[b][font color=""Red""]";
var append = @"[/font][/b]";

string outputString = "";
foreach (Match match in matches)
{
    outputString += prepend + match.Groups[1] + append + match.Groups[2] + Environment.NewLine;
}

Console.Out.WriteLine(outputString);

OTHER TIPS

have you tried .Insert() check this.

Have you considered creating a style and setting the css class of each line by wrapping each line in a p or div tag?

Easier to maintain and to construct.

The easiest way probably is to use string.Replace() and string.Split(). Say your input string is input (untested):

var output = string.Join("<br/>", in
    .Split("<br/>)
    .Select(l => "<b><font color=\"Red\">" + l.Replace(": ", "</font></b>: "))
    .ToList()
    ) + "<br/>";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top