" for the whole file I would like to count the number of characters betwee...">

Count the number of characters between opening and closing "<" and ">" for the whole file

I would like to count the number of characters between opening and closing '<' and '>' for the whole file (e.g., <tag>bla<tag> == 6). I could always write a quick algorithm to do this, but I'm curious to know if there is another way. Maybe a regular expression?

thank

+3
source share
4 answers

You can do it with regex as follows:

var brackets = new char[] {'<', '>'};
int counter = 0;
foreach (var match in System.Text.RegularExpressions.Regex.Matches(data, @"</?[^<>]+>"))
  counter += match.ToString().Trim(brackets).TrimStart('/').Length;

This also correctly considers end tags if you have tags too.

+1
source

, , , , :

        string s = System.IO.File.ReadAllText("myfile.txt");
        bool inbrackets = false;
        int count = 0;
        foreach (char ch in s)
        {
            if (ch == '<')
                inbrackets = true;
            else if (ch == '>')
                inbrackets = false;
            else if (inbrackets)
                ++count;
        }

        System.Console.WriteLine("count = " + count);

. , int bool. , , .

+2

Assuming there are no nesting shortcuts and you have well-formed input

var charcount = File.ReadAllText("C:\foo.txt").Split('<')
   .Select(x => x.IndexOf('>')).Where(x => x > 0).Sum();

If you have nesting or require error checking, obviously, you will need to write something more thorough.

0
source
int sum = new Regex("<([^<>]+?)>").Matches("<tag>bla<tag>")
                                  .Cast<Match>()
                                  .Sum(m => m.Value.Length - 2);
        = 6
0
source

All Articles