Показать сообщение отдельно

  #10  
Старый 06.03.2009, 03:06
Algol
Регистрация: 29.05.2002
Сообщений: 1,793
С нами: 12604706

Репутация: 0


По умолчанию

Цитата:
Сообщение от HencH_MaN  
Это программирование. Поподробнее про регекс.
C#:
Код:
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication7
{
    class Program
    {
        static void Main(string[] args)
        {
            string source = 
@"
/*This is example*/
#include <iostream>   // для использования std::cout
#include <vector>     // для std::vector<>
#include <map>        // для std::map<> и std::pair<>
#include <algorithm>  // для std::for_each()
#include <string>     // для std::string
 
 
using namespace std;  // используем пространство имён ""std""
 
void display_item_count(pair< string const, vector<string> > const& person) {
   // person - это пара двух объектов: person.first - это его имя,
   // person.second - это список его предметов (вектор строк)
   cout << person.first << "" is carrying "" << person.second.size() << "" items"" << endl;
}
 
int main()
{
   // объявляем карту со строковыми ключами и данными в виде векторов строк
   map< string, vector<string> > items;
 
   // Добавим в эту карту пару человек и дадим им несколько предметов
   items[""Anya""].push_back(""scarf"");
   items[""Dimitri""].push_back(""tickets"");
   items[""Anya""].push_back(""puppy"");
 
   // Переберём все объекты в контейнере
   for_each(items.begin(), items.end(), display_item_count);
}
";
            //вырезаем содержимое кавычек
            string quotePattern = "(\"[^\"]*\")";
            source = Regex.Replace(source, quotePattern, "");

            //отрезаем комментарии
            string commentPattern = "(//.+?)$";
            source = Regex.Replace(source, commentPattern, "", RegexOptions.Multiline);
            commentPattern = "(/\\*.+?\\*/)";
            source = Regex.Replace(source, commentPattern, "");

            //убираем зарезервированные слова
            string keywordPattern = "\\b(__abstract|abstract|__alignof Operator|array|__asm|__assume|__based|bool|__box|break|case|catch|__cdecl|char|class|const|const_cast|continue|cout|__declspec|default|__delegate|delegate|delete|deprecated|dllexport|dllimport|do|double|dynamic_cast|else|enum|enum class|enum struct|event|__event|__except|explicit|extern|false|__fastcall|__finally|finally|float|for|for_each|in|__forceinline|friend|friend_as|__gc|gcnew|generic|goto|__hook|__identifier|if|__if_exists|__if_not_exists|include|initonly|__inline|inline|int|__int8|__int16|__int32|__int64|__interface|interface class|interface struct|interior_ptr|__leave|literal|long|__m64|__m128|__m128d|__m128i|__multiple_inheritance|mutable|naked|namespace|new|new|__nogc|noinline|__noop|noreturn|nothrow|novtable|nullptr|operator|__pin|private|__property|property|property|protected|public|__raise|ref struct|ref class|register|reinterpret_cast|return|safecast|__sealed|sealed|selectany|short|signed|__single_inheritance|sizeof|static|static_cast|__stdcall|struct|__super|switch|template|this|thread|throw|true|try|__try|__except|__finally|__try_cast|typedef|typeid|typeid|typename|__unaligned|__unhook|union|unsigned|using declaration|using directive|uuid|__uuidof|value struct|value class|__value|virtual|__virtual_inheritance|void|volatile|__w64|__wchar_t|wchar_t|while)\\b";
            source = Regex.Replace(source, keywordPattern, "", RegexOptions.Multiline);

            //ищем идентификаторы, заносим в хештаблицу
            string idPattern = "\\b[a-zA-Z_][a-zA-Z0-9_]*\\b";
            Dictionary<string, byte> ids = new Dictionary<string, byte>();
            foreach (Match m in Regex.Matches(source, idPattern))
                ids[m.Groups[0].Value] = 0;

            //выводим
            foreach (string id in ids.Keys)
                Console.WriteLine(id);

            Console.ReadLine();
        }
    }
}
 
Ответить с цитированием