Reputation: 2374
I need to parse some text from some files and split ti by parts, depends on is it simple text part of text or html.
Let's say, this is example text
This section should include any considerations for:
<ul>
<li>C</li>
<li>B</li>
<li>A</li>
</ul>
h1. Support Contracts
<p>simple par</p>
And it should be splitted like that (used JSON notation, because of it was fast to write, doesnt matter what type of the container is there)
[{
part: 1,
text: "This section should include any considerations for:"
},
{
part: 2,
text:"<ul> <li>C</li><li>B</li> <li>A</li></ul>"
},
{
part: 3,
text:"h1. Support Contracts"
},
{
part: 4,
text:"<p>simple par</p>"
}]
Html there is really simple and all tags are guaranteed closed (it generated by program)
What the way is most faster (without using any third-party libs)? Can I use regex here for this task?
Upvotes: 1
Views: 71
Reputation: 17428
If I am understanding your requirements properly, I am not sure I would tackle this with a regular expression. It seems like it would be simple enough to just walk the text looking for the tags and building a list of pieces as you go.
var pieces = new List<string>();
int current = 0;
while (current < text.Length)
{
var first = text.IndexOf('<', current);
if (first != -1)
{
var second = text.IndexOf('>', first);
if (second != -1)
{
var tag = text.Substring(first+1, (second-first-1));
var closeTag = $"</{tag}>";
var close = text.IndexOf(closeTag, second+1);
if (close != -1)
{
close += closeTag.Length;
if (current < first)
{
pieces.Add(text.Substring(current, (first-current)).Trim());
}
current = close + 1;
pieces.Add(text.Substring(first, (close-first)).Trim());
}
else
{
current = second + 1;
}
}
else
{
current = first+1;
}
}
else
{
pieces.Add(text.Substring(current).Trim());
break;
}
}
Upvotes: 1