Карта сайта Kansoftware
НОВОСТИУСЛУГИРЕШЕНИЯКОНТАКТЫ
Разработка программного обеспечения

Unicode Aware Regex Iterators

Boost , Boost.Regex 5.1.2 , Working With Unicode and ICU String Types

Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

PrevUpHomeNext
u32regex_iterator

Тип<u32regex_iterator>во всех отношениях тот же, что и<regex_iterator>, за исключением того, что, поскольку тип регулярного выражения всегда<u32regex>, он принимает только один параметр шаблона (тип итератора). Он также вызывает<u32regex_search>внутренне, что позволяет ему правильно взаимодействовать с данными UTF-8, UTF-16 и UTF-32:

template <class BidirectionalIterator>
class u32regex_iterator
{
   // for members see regex_iterator
};
typedef u32regex_iterator<const char*>     utf8regex_iterator;
typedef u32regex_iterator<const UChar*>    utf16regex_iterator;
typedef u32regex_iterator<const UChar32*>  utf32regex_iterator;

Чтобы упростить конструкцию<u32regex_iterator>из строки, существует ряд вспомогательных функций, называемых make_u32regex_iterator:

u32regex_iterator<const char*>
   make_u32regex_iterator(const char* s,
                          const u32regex& e,
                          regex_constants::match_flag_type m = regex_constants::match_default);
u32regex_iterator<const wchar_t*>
   make_u32regex_iterator(const wchar_t* s,
                          const u32regex& e,
                          regex_constants::match_flag_type m = regex_constants::match_default);
u32regex_iterator<const UChar*>
   make_u32regex_iterator(const UChar* s,
                          const u32regex& e,
                          regex_constants::match_flag_type m = regex_constants::match_default);
template <class charT, class Traits, class Alloc>
u32regex_iterator<typename std::basic_string<charT, Traits, Alloc>::const_iterator>
   make_u32regex_iterator(const std::basic_string<charT, Traits, Alloc>& s,
                          const u32regex& e,
                          regex_constants::match_flag_type m = regex_constants::match_default);
u32regex_iterator<const UChar*>
   make_u32regex_iterator(const UnicodeString& s,
                          const u32regex& e,
                          regex_constants::match_flag_type m = regex_constants::match_default);

Каждая из этих перегрузок возвращает итератор, который перечисляет все случаи выраженияe, в текстеs, используя match_flagsм.

Пример: поиск международных валютных символов, а также связанных с ними цифровых значений:

void enumerate_currencies(const std::string& text)
{
   // enumerate and print all the currency symbols, along
   // with any associated numeric values:
   const char* re =
      "([[:Sc:]][[:Cf:][:Cc:][:Z*:]]*)?"
      "([[:Nd:]]+(?:[[:Po:]][[:Nd:]]+)?)?"
      "(?(1)"
         "|(?(2)"
            "[[:Cf:][:Cc:][:Z*:]]*"
         ")"
         "[[:Sc:]]"
      ")";
   boost::u32regex r = boost::make_u32regex(re);
   boost::u32regex_iterator<std::string::const_iterator>
         i(boost::make_u32regex_iterator(text, r)), j;
   while(i != j)
   {
      std::cout << (*i)[0] << std::endl;
      ++i;
   }
}

Звонок

enumerate_currencies(" $100.23 or £198.12 ");

Производительность:

$100.23
£198.12

При условии, что вход кодируется как UTF-8.

u32regex_token_iterator

Тип<u32regex_token_iterator>во всех отношениях такой же, как<regex_token_iterator>, за исключением того, что, поскольку тип регулярного выражения всегда<u32regex>, он принимает только один параметр шаблона (тип итератора). Он также вызывает<u32regex_search>внутренне, что позволяет ему правильно взаимодействовать с данными UTF-8, UTF-16 и UTF-32:

template <class BidirectionalIterator>
class u32regex_token_iterator
{
   // for members see regex_token_iterator
};
typedef u32regex_token_iterator<const char*>     utf8regex_token_iterator;
typedef u32regex_token_iterator<const UChar*>    utf16regex_token_iterator;
typedef u32regex_token_iterator<const UChar32*>  utf32regex_token_iterator;

Чтобы упростить конструкцию<u32regex_token_iterator>из струны, существует ряд вспомогательных функций, называемых<make_u32regex_token_iterator>:

u32regex_token_iterator<const char*>
   make_u32regex_token_iterator(
         const char* s,
         const u32regex& e,
         int sub,
         regex_constants::match_flag_type m = regex_constants::match_default);
u32regex_token_iterator<const wchar_t*>
   make_u32regex_token_iterator(
         const wchar_t* s,
         const u32regex& e,
         int sub,
         regex_constants::match_flag_type m = regex_constants::match_default);
u32regex_token_iterator<const UChar*>
   make_u32regex_token_iterator(
         const UChar* s,
         const u32regex& e,
         int sub,
         regex_constants::match_flag_type m = regex_constants::match_default);
template <class charT, class Traits, class Alloc>
u32regex_token_iterator<typename std::basic_string<charT, Traits, Alloc>::const_iterator>
   make_u32regex_token_iterator(
         const std::basic_string<charT, Traits, Alloc>& s,
         const u32regex& e,
         int sub,
         regex_constants::match_flag_type m = regex_constants::match_default);
u32regex_token_iterator<const UChar*>
   make_u32regex_token_iterator(
         const UnicodeString& s,
         const u32regex& e,
         int sub,
         regex_constants::match_flag_type m = regex_constants::match_default);

Каждая из этих перегрузок возвращает итератор, который перечисляет все случаи отмеченной субэкспрессии в регулярном выраженииe, найденный в текстеs, с использованием match_flagsm.

template <std::size_t N>
u32regex_token_iterator<const char*>
   make_u32regex_token_iterator(
         const char* p,
         const u32regex& e,
         const int (&submatch)[N],
         regex_constants::match_flag_type m = regex_constants::match_default);
template <std::size_t N>
u32regex_token_iterator<const wchar_t*>
   make_u32regex_token_iterator(
         const wchar_t* p,
         const u32regex& e,
         const int (&submatch)[N],
         regex_constants::match_flag_type m = regex_constants::match_default);
template <std::size_t N>
u32regex_token_iterator<const UChar*>
   make_u32regex_token_iterator(
         const UChar* p,
         const u32regex& e,
         const int (&submatch)[N],
         regex_constants::match_flag_type m = regex_constants::match_default);
template <class charT, class Traits, class Alloc, std::size_t N>
u32regex_token_iterator<typename std::basic_string<charT, Traits, Alloc>::const_iterator>
   make_u32regex_token_iterator(
         const std::basic_string<charT, Traits, Alloc>& p,
         const u32regex& e,
         const int (&submatch)[N],
         regex_constants::match_flag_type m = regex_constants::match_default);
template <std::size_t N>
u32regex_token_iterator<const UChar*>
   make_u32regex_token_iterator(
         const UnicodeString& s,
         const u32regex& e,
         const int (&submatch)[N],
         regex_constants::match_flag_type m = regex_constants::match_default);

Каждая из этих перегрузок возвращает итератор, который перечисляет одно подвыражение для каждого подматча в обычном выраженииe, найденное в текстеs, с использованием match_flagsm.

u32regex_token_iterator<const char*>
   make_u32regex_token_iterator(
         const char* p,
         const u32regex& e,
         const std::vector<int>& submatch,
         regex_constants::match_flag_type m = regex_constants::match_default);
u32regex_token_iterator<const wchar_t*>
   make_u32regex_token_iterator(
         const wchar_t* p,
         const u32regex& e,
         const std::vector<int>& submatch,
         regex_constants::match_flag_type m = regex_constants::match_default);
u32regex_token_iterator<const UChar*>
   make_u32regex_token_iterator(
         const UChar* p,
         const u32regex& e,
         const std::vector<int>& submatch,
         regex_constants::match_flag_type m = regex_constants::match_default);
template <class charT, class Traits, class Alloc>
u32regex_token_iterator<typename std::basic_string<charT, Traits, Alloc>::const_iterator>
   make_u32regex_token_iterator(
         const std::basic_string<charT, Traits, Alloc>& p,
         const u32regex& e,
         const std::vector<int>& submatch,
         regex_constants::match_flag_type m = regex_constants::match_default);
u32regex_token_iterator<const UChar*>
   make_u32regex_token_iterator(
         const UnicodeString& s,
         const u32regex& e,
         const std::vector<int>& submatch,
         regex_constants::match_flag_type m = regex_constants::match_default);

Каждая из этих перегрузок возвращает итератор, который перечисляет одно подвыражение для каждого подматча в обычном выраженииe, найденное в текстеs, с использованием match_flagsm.

Пример: поиск международных валютных символов, а также связанных с ними цифровых значений:

void enumerate_currencies2(const std::string& text)
{
   // enumerate and print all the currency symbols, along
   // with any associated numeric values:
   const char* re =
      "([[:Sc:]][[:Cf:][:Cc:][:Z*:]]*)?"
      "([[:Nd:]]+(?:[[:Po:]][[:Nd:]]+)?)?"
      "(?(1)"
         "|(?(2)"
            "[[:Cf:][:Cc:][:Z*:]]*"
         ")"
         "[[:Sc:]]"
      ")";
   boost::u32regex r = boost::make_u32regex(re);
   boost::u32regex_token_iterator<std::string::const_iterator>
      i(boost::make_u32regex_token_iterator(text, r, 1)), j;
   while(i != j)
   {
      std::cout << *i << std::endl;
      ++i;
   }
}

PrevUpHomeNext

Статья Unicode Aware Regex Iterators раздела Boost.Regex 5.1.2 Working With Unicode and ICU String Types может быть полезна для разработчиков на c++ и boost.




Материалы статей собраны из открытых источников, владелец сайта не претендует на авторство. Там где авторство установить не удалось, материал подаётся без имени автора. В случае если Вы считаете, что Ваши права нарушены, пожалуйста, свяжитесь с владельцем сайта.



:: Главная :: Working With Unicode and ICU String Types ::


реклама


©KANSoftWare (разработка программного обеспечения, создание программ, создание интерактивных сайтов), 2007
Top.Mail.Ru

Время компиляции файла: 2024-08-30 11:47:00
2025-07-04 20:07:19/0.028897047042847/1