246 lines
10 KiB
C++
246 lines
10 KiB
C++
//! \~\file piregularexpression.h
|
||
//! \~\ingroup Text
|
||
//! \brief
|
||
//! \~english Regular expression
|
||
//! \~russian Регулярное выражение
|
||
/*
|
||
PIP - Platform Independent Primitives
|
||
Regular expression
|
||
Ivan Pelipenko peri4ko@yandex.ru
|
||
|
||
This program is free software: you can redistribute it and/or modify
|
||
it under the terms of the GNU Lesser General Public License as published by
|
||
the Free Software Foundation, either version 3 of the License, or
|
||
(at your option) any later version.
|
||
|
||
This program is distributed in the hope that it will be useful,
|
||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||
GNU Lesser General Public License for more details.
|
||
|
||
You should have received a copy of the GNU Lesser General Public License
|
||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||
*/
|
||
|
||
#ifndef PIREGULAREXPRESSION_H
|
||
#define PIREGULAREXPRESSION_H
|
||
|
||
#include "pistring.h"
|
||
|
||
//! \~\ingroup Text
|
||
//! \~\brief
|
||
//! \~english Regular expression class.
|
||
//! \~russian Класс регулярного выражения.
|
||
class PIP_EXPORT PIRegularExpression {
|
||
public:
|
||
//! \~english Matching options.
|
||
//! \~russian Опции сопоставления.
|
||
enum Option {
|
||
None = 0x0 /*!< \~english No extra options \~russian Без дополнительных опций */,
|
||
CaseInsensitive = 0x01 /*!< \~english Ignore character case \~russian Игнорировать регистр символов */,
|
||
Singleline = 0x02 /*!< \~english Let \c . match a newline \~russian Разрешить \c . совпадать с переводом строки */,
|
||
Multiline =
|
||
0x04 /*!< \~english Let \c ^ and \c $ work on line boundaries \~russian Разрешить \c ^ и \c $ работать на границах строк */,
|
||
InvertedGreediness =
|
||
0x08 /*!< \~english Make quantifiers non-greedy by default \~russian Сделать квантификаторы по умолчанию нежадными */,
|
||
Extended = 0x10 /*!< \~english Use extended pattern syntax \~russian Использовать расширенный синтаксис шаблона */
|
||
};
|
||
|
||
//! \~english Flag set of \a Option values.
|
||
//! \~russian Набор флагов \a Option.
|
||
typedef PIFlags<Option> Options;
|
||
|
||
|
||
//! \~english Creates a regular expression from \a pattern and \a opt.
|
||
//! \~russian Создает регулярное выражение из \a pattern и \a opt.
|
||
PIRegularExpression(const PIString & pattern = {}, Options opt = None);
|
||
|
||
|
||
//! \~english Creates a copy of another regular expression.
|
||
//! \~russian Создает копию другого регулярного выражения.
|
||
PIRegularExpression(const PIRegularExpression & o);
|
||
|
||
|
||
//! \~english Assigns another regular expression.
|
||
//! \~russian Присваивает другое регулярное выражение.
|
||
PIRegularExpression & operator=(const PIRegularExpression & o);
|
||
|
||
|
||
//! \~english Destroys the regular expression object.
|
||
//! \~russian Уничтожает объект регулярного выражения.
|
||
~PIRegularExpression();
|
||
|
||
|
||
//! \~\brief
|
||
//! \~english Match result and iterator state.
|
||
//! \~russian Результат сопоставления и состояние итерации.
|
||
class PIP_EXPORT Matcher {
|
||
friend class PIRegularExpression;
|
||
|
||
public:
|
||
//! \~english Returns \c true when a match is available.
|
||
//! \~russian Возвращает \c true, если найдено совпадение.
|
||
operator bool() const { return hasMatch(); }
|
||
|
||
//! \~english Returns \c true when a match is available.
|
||
//! \~russian Возвращает \c true, если найдено совпадение.
|
||
bool hasMatch() const;
|
||
|
||
//! \~english Advances to the next match in the same subject.
|
||
//! \~russian Переходит к следующему совпадению в той же строке.
|
||
bool next();
|
||
|
||
|
||
//! \~english Returns all captured strings of the current match.
|
||
//! \~russian Возвращает все захваченные строки текущего совпадения.
|
||
PIStringList matchedStrings() const;
|
||
|
||
|
||
//! \~english Returns the captured substring at \a index.
|
||
//! \~russian Возвращает захваченную подстроку по \a index.
|
||
PIString matchedString(int index = 0) const;
|
||
|
||
//! \~english Returns the start position of the capture at \a index.
|
||
//! \~russian Возвращает начальную позицию захвата по \a index.
|
||
int matchedStart(int index = 0) const;
|
||
|
||
//! \~english Returns the size of the capture at \a index.
|
||
//! \~russian Возвращает длину захвата по \a index.
|
||
int matchedSize(int index = 0) const;
|
||
|
||
|
||
//! \~english Returns the captured substring of named group \a gname.
|
||
//! \~russian Возвращает захваченную подстроку именованной группы \a gname.
|
||
PIString matchedString(const PIString & gname) const;
|
||
|
||
//! \~english Returns the start position of named group \a gname.
|
||
//! \~russian Возвращает начальную позицию именованной группы \a gname.
|
||
int matchedStart(const PIString & gname) const;
|
||
|
||
//! \~english Returns the size of the named group \a gname.
|
||
//! \~russian Возвращает длину именованной группы \a gname.
|
||
int matchedSize(const PIString & gname) const;
|
||
|
||
//! \~english Move constructor.
|
||
//! \~russian Перемещающий конструктор.
|
||
Matcher(Matcher &&) = default;
|
||
|
||
private:
|
||
Matcher(PIRegularExpression * p);
|
||
Matcher(const Matcher &) = default;
|
||
Matcher & operator=(const Matcher &) = default;
|
||
|
||
struct Group {
|
||
int index = 0;
|
||
int size = 0;
|
||
};
|
||
|
||
PIChar * subjectPtr() const;
|
||
|
||
bool has_match = false;
|
||
bool is_error = false;
|
||
PIVector<Group> groups;
|
||
PIRegularExpression * parent = nullptr;
|
||
PIString * subject = nullptr;
|
||
PIString subject_own;
|
||
size_t start_offset = 0;
|
||
};
|
||
|
||
|
||
//! \~english Returns the stored pattern.
|
||
//! \~russian Возвращает сохраненный шаблон.
|
||
PIString pattern() const { return pat_; }
|
||
|
||
//! \~english Returns the stored options.
|
||
//! \~russian Возвращает сохраненные опции.
|
||
Options options() const { return opt_; }
|
||
|
||
|
||
//! \~english Replaces the pattern and keeps current options.
|
||
//! \~russian Заменяет шаблон и сохраняет текущие опции.
|
||
void setPattern(const PIString & pattern);
|
||
|
||
//! \~english Replaces the pattern and options.
|
||
//! \~russian Заменяет шаблон и опции.
|
||
void setPattern(const PIString & pattern, Options opt);
|
||
|
||
|
||
//! \~english Returns \c true when the compiled pattern is valid.
|
||
//! \~russian Возвращает \c true, если скомпилированный шаблон корректен.
|
||
bool isValid() const;
|
||
|
||
//! \~english Returns \c true when the pattern is invalid.
|
||
//! \~russian Возвращает \c true, если шаблон некорректен.
|
||
bool isNotValid() const { return !isValid(); }
|
||
|
||
|
||
//! \~english Returns the compilation error text for an invalid pattern.
|
||
//! \~russian Возвращает текст ошибки компиляции для некорректного шаблона.
|
||
PIString errorString() const;
|
||
|
||
//! \~english Returns the error position inside the pattern.
|
||
//! \~russian Возвращает позицию ошибки внутри шаблона.
|
||
int errorPosition() const;
|
||
|
||
|
||
//! \~english Returns the number of capture groups in the pattern.
|
||
//! \~russian Возвращает количество групп захвата в шаблоне.
|
||
int captureGroupsCount() const;
|
||
|
||
//! \~english Returns the names of all named capture groups.
|
||
//! \~russian Возвращает имена всех именованных групп захвата.
|
||
PIStringList captureGroupNames() const;
|
||
|
||
//! \~english Returns the capture group name by index.
|
||
//! \~russian Возвращает имя группы захвата по индексу.
|
||
PIString captureGroupName(int index) const;
|
||
|
||
//! \~english Returns the index of named capture group `gname`.
|
||
//! \~russian Возвращает индекс именованной группы захвата `gname`.
|
||
int captureGroupIndex(const PIString & gname) const;
|
||
|
||
|
||
//! \~english Matches against an internal copy of \a subject.
|
||
//! \~russian Выполняет сопоставление по внутренней копии \a subject.
|
||
Matcher match(const PIString & subject, size_t offset = 0) const;
|
||
|
||
//! \~english Matches against \a subject by reference.
|
||
//! \~russian Выполняет сопоставление со \a subject по ссылке.
|
||
Matcher match(PIString & subject, size_t offset = 0) const;
|
||
|
||
//! \~english Matches against an rvalue \a subject.
|
||
//! \~russian Выполняет сопоставление с временной строкой \a subject.
|
||
Matcher match(PIString && subject, size_t offset = 0) const;
|
||
|
||
|
||
//! \~english Prepares an iterator-style matcher over an internal copy of \a subject.
|
||
//! \~russian Подготавливает итератор сопоставлений по внутренней копии \a subject.
|
||
Matcher matchIterator(const PIString & subject, size_t offset = 0) const;
|
||
|
||
//! \~english Prepares an iterator-style matcher over \a subject.
|
||
//! \~russian Подготавливает итератор сопоставлений по \a subject.
|
||
Matcher matchIterator(PIString & subject, size_t offset = 0) const;
|
||
|
||
//! \~english Prepares an iterator-style matcher over an rvalue \a subject.
|
||
//! \~russian Подготавливает итератор сопоставлений по временной строке \a subject.
|
||
Matcher matchIterator(PIString && subject, size_t offset = 0) const;
|
||
|
||
|
||
//! \~english Builds a regular expression from a glob pattern.
|
||
//! \~russian Создает регулярное выражение из glob-шаблона.
|
||
static PIRegularExpression fromGlob(const PIString & pattern, Options opt = None);
|
||
|
||
//! \~english Builds a regular expression from a POSIX pattern.
|
||
//! \~russian Создает регулярное выражение из POSIX-шаблона.
|
||
static PIRegularExpression fromPOSIX(const PIString & pattern, Options opt = None);
|
||
|
||
private:
|
||
void convertFrom(const PIString & pattern, uint type, Options opt);
|
||
|
||
PRIVATE_DECLARATION(PIP_EXPORT)
|
||
PIString pat_;
|
||
Options opt_;
|
||
};
|
||
|
||
#endif // PIREGULAREXPRESSION_H
|