wxWidgets: wxRegEx Class Reference

| Version: 3.1.7

Loading...
Searching...
No Matches
Public Member Functions | Static Public Member Functions | List of all members
wxRegEx Class Reference
Class List by Category » Data Structures

`#include </cygdrive/c/Users/Hamis/Cygwin-packaging/wxWidgets3.1/wxWidgets3.1-3.1.7-1.x86_64/src/wxWidgets-3.1.7/interface/wx/regex.h>`

## Detailed Description

wxRegEx represents a regular expression.

This class provides support for regular expressions matching and also replacement.

In wxWidgets 3.1.6 or later, it is built on top of PCRE library (https://www.pcre.org/). In the previous versions of wxWidgets, this class uses Henry Spencer's library and behaved slightly differently, see below for the discussion of the changes if you're upgrading from an older version.

Note that while C++11 and later provides `std::regex` and related classes, this class is still useful as it provides the following important advantages:

- Support for richer regular expressions syntax.
- Much better performance in many common cases, by a factor of 10-100.
- Consistent behaviour, including performance, on all platforms.

##

Library: wxBase
Category: Data Structures

Example:

A (bad) example of processing some text containing email addresses (the example is bad because the real email addresses can have more complicated form than `user@.nosp@m.host.nosp@m..net`):

wxString originalText = "This is some text with foo@example.com and bar@example.com";
// Regex. to match an email address and extract its subparts.
wxRegEx reEmail("([^@ -]+)@([[:alnum:]_]+).([[:alnum:]]{2,4})");
wxString processText = originalText;
while ( reEmail.Matches(processText) )
{
// Find the size of the first match and print it.
size_t start, len;
reEmail.GetMatch(&start, &len, 0);
std::cout << "Email: " << reEmail.GetMatch(processText, 0) << std::endl;
// Print the submatches.
std::cout << "Name: " << reEmail.GetMatch(processText, 1) << std::endl;
std::cout << "Domain: " << reEmail.GetMatch(processText, 2) << std::endl;
std::cout << "TLD: " << reEmail.GetMatch(processText, 3) << std::endl;
// Process the remainder of the text if there is any.
processText = processText.Mid (start + len);
}
// Or this will replace all names with "HIDDEN".
size_t count = reEmail.ReplaceAll(&originalText, "HIDDEN@\\2.\\3");
std::cout << "text now contains " << count << " hidden addresses" << std::endl;
std::cout << originalText << std::endl;
wxRegEx::wxRegEx
wxRegEx()
Default constructor: use Compile() later.
wxString
String class for passing textual data to or receiving it from wxWidgets.
Definition string.h:315
wxString::Mid
wxString Mid(size_t first, size_t nCount=wxString::npos) const
Returns a substring starting at first, with length count, or the rest of the string if count is the d...

# Changes in the PCRE-based version

This section describes the difference in regex syntax in the new PCRE-based wxRegEx version compared to the previously used version which implemented POSIX regex support.

The main change is that both extended (wxRE_EXTENDED) and advanced (wxRE_ADVANCED) regex syntax is now the same as PCRE syntax described at https://www.pcre.org/current/doc/html/pcre2syntax.html

Basic regular expressions (wxRE_BASIC) are still different, but their use is deprecated and PCRE extensions are still accepted in them, please avoid using them.

Other changes are:

- Negated character classes, i.e. ``[^....], now always match newline character, regardless of whether wxRE_NEWLINE was used or not. The dot metacharacter still has the same meaning, i.e. it matches newline by default but not when wxRE_NEWLINE is specified.
- Previously POSIX-specified behaviour of handling unmatched right parenthesis `'`)' as a literal character was implemented, but now this is a (regex) compilation error.
- Empty alternation branches were previously ignored, i.e. matching `a||b` worked the same as matching just `a|b`, but now actually matches an empty string. The new wxRE_NOTEMPTY flag can be used to disable empty matches.
- Using `\U` to embed Unicode code points into the pattern is not supported any more, use the still supported `\u`, followed by exactly four hexadecimal digits, or `\x`, followed by exactly two hexadecimal digits, instead.
- POSIX collating elements inside square brackets, i.e. ``[.XXX.] and ``[:XXXX:] are not supported by PCRE and result in regex compilation errors.
- Backslash can be used to escape the character following it even inside square brackets now, while it loses its special meaning in POSIX regexes when it occurs inside square brackets. In particular, `"\\‍]"` escapes the special meaning of the closing bracket, and so does not close the character class. Please use `"\\\\‍]"` instead.
- Closing parenthesis without a matching open parenthesis is now a syntax error instead of just being treated as a literal. To fix possible errors due to it, escape parenthesis that are supposed to be taken literally with a backslash, i.e. use `"\\‍)"` in C strings.
- For completeness, PCRE syntax which previously resulted in errors, e.g. `"(?:...)"` and similar constructs, are now accepted and behave as expected. Other regexes syntactically invalid according to POSIX are re-interpreted as sequences of literal characters with PCRE, e.g. `"{1"` is just a sequence of two literal characters now, where it previously was a compilation error.

## Public Member Functions
| wxRegEx ()
| Default constructor: use Compile() later.
| wxRegEx (const wxString &expr, int flags=wxRE_DEFAULT)
| Create and compile the regular expression, use IsValid() to test for compilation errors.
| ~wxRegEx ()
| Destructor.
bool | Compile (const wxString &pattern, int flags=wxRE_DEFAULT)
| Compile the string into regular expression, return true if ok or false if string has a syntax error.
bool | GetMatch (size_t *start, size_t *len, size_t index=0) const
| Get the start index and the length of the match of the expression (if index is 0) or a bracketed subexpression (index different from 0).
wxString | GetMatch (const wxString &text, size_t index=0) const
| Returns the part of string corresponding to the match where index is interpreted as above.
size_t | GetMatchCount () const
| Returns the size of the array of matches, i.e. the number of bracketed subexpressions plus one for the expression itself, or 0 on error.
bool | IsValid () const
| Return true if this is a valid compiled regular expression, false otherwise.
bool | Matches (const wxChar *text, int flags=0) const
| Matches the precompiled regular expression against the string text, returns true if matches and false otherwise.
bool | Matches (const wxChar *text, int flags, size_t len) const
bool | Matches (const wxString &text, int flags=0) const
| Matches the precompiled regular expression against the string text, returns true if matches and false otherwise.
int | Replace (wxString *text, const wxString &replacement, size_t maxMatches=0) const
| Replaces the current regular expression in the string pointed to by text, with the text in replacement and return number of matches replaced (maybe 0 if none found) or -1 on error.
int | ReplaceAll (wxString *text, const wxString &replacement) const
| Replace all occurrences: this is actually a synonym for Replace().
int | ReplaceFirst (wxString *text, const wxString &replacement) const
| Replace the first occurrence.

## Static Public Member Functions
static wxString | QuoteMeta (const wxString &str)
| Escapes any of the characters having special meaning for wxRegEx.
static wxString | ConvertFromBasic (const wxString &bre)
| Converts a basic regular expression to an extended regex syntax.
static wxVersionInfo | GetLibraryVersionInfo ()
| Return the version of PCRE used.

## Constructor & Destructor Documentation

## ◆ wxRegEx() [1/2]

wxRegEx::wxRegEx | ( |  | ) |

Default constructor: use Compile() later.

## ◆ wxRegEx() [2/2]

wxRegEx::wxRegEx | ( | const wxString & | expr,
|  | int | flags = wxRE_DEFAULT )

Create and compile the regular expression, use IsValid() to test for compilation errors.

As for the flags, please see wxRE_FLAGS.

## ◆ ~wxRegEx()

wxRegEx::~wxRegEx | ( |  | ) |

Destructor.

It's not virtual, don't derive from this class.

## Member Function Documentation

## ◆ Compile()

bool wxRegEx::Compile | ( | const wxString & | pattern,
|  | int | flags = wxRE_DEFAULT )

Compile the string into regular expression, return true if ok or false if string has a syntax error.

As for the flags, please see wxRE_FLAGS.

## ◆ ConvertFromBasic()

wxString wxRegEx::ConvertFromBasic | ( | const wxString & | bre | ) |
| static

Converts a basic regular expression to an extended regex syntax.

This function can be used to convert bre using deprecated wxRE_BASIC syntax to default (extended) syntax.

Since
  3.1.6

## ◆ GetLibraryVersionInfo()

wxVersionInfo wxRegEx::GetLibraryVersionInfo | ( |  | ) |
| static

Return the version of PCRE used.

The returned wxVersionInfo object currently always has its micro version component set to 0, as PCRE uses only major and minor version components. Its description component contains the version number, release date and, for pre-release PCRE versions, a mention of it.

Since
  3.1.6

## ◆ GetMatch() [1/2]

wxString wxRegEx::GetMatch | ( | const wxString & | text,
|  | size_t | index = 0 ) const

Returns the part of string corresponding to the match where index is interpreted as above.

Empty string is returned if match failed.

May only be called after successful call to Matches() and only if `wxRE_NOSUB` was not used in Compile().

## ◆ GetMatch() [2/2]

bool wxRegEx::GetMatch | ( | size_t * | start,
|  | size_t * | len,
|  | size_t | index = 0 ) const

Get the start index and the length of the match of the expression (if index is 0) or a bracketed subexpression (index different from 0).

May only be called after successful call to Matches() and only if `wxRE_NOSUB` was not used in Compile().

Returns false if no match or if an error occurred.

## ◆ GetMatchCount()

size_t wxRegEx::GetMatchCount | ( |  | ) | const

Returns the size of the array of matches, i.e. the number of bracketed subexpressions plus one for the expression itself, or 0 on error.

May only be called after successful call to Compile(). and only if `wxRE_NOSUB` was not used.

## ◆ IsValid()

bool wxRegEx::IsValid | ( |  | ) | const

Return true if this is a valid compiled regular expression, false otherwise.

## ◆ Matches() [1/3]

bool wxRegEx::Matches | ( | const wxChar * | text,
|  | int | flags,
|  | size_t | len ) const

## ◆ Matches() [2/3]

bool wxRegEx::Matches | ( | const wxChar * | text,
|  | int | flags = 0 ) const

Matches the precompiled regular expression against the string text, returns true if matches and false otherwise.

Flags may be combination of `wxRE_NOTBOL` and `wxRE_NOTEOL`, see wxRE_NOT_FLAGS.

Some regex libraries assume that the text given is null terminated, while others require the length be given as a separate parameter. Therefore for maximum portability assume that text cannot contain embedded nulls.

When the Matches(const wxChar *text, int flags = 0) form is used, a wxStrlen() will be done internally if the regex library requires the length. When using Matches() in a loop the Matches(text, flags, len) form can be used instead, making it possible to avoid a wxStrlen() inside the loop.

May only be called after successful call to Compile().

## ◆ Matches() [3/3]

bool wxRegEx::Matches | ( | const wxString & | text,
|  | int | flags = 0 ) const

Matches the precompiled regular expression against the string text, returns true if matches and false otherwise.

Flags may be combination of `wxRE_NOTBOL` and `wxRE_NOTEOL`, see wxRE_NOT_FLAGS.

May only be called after successful call to Compile().

## ◆ QuoteMeta()

wxString wxRegEx::QuoteMeta | ( | const wxString & | str | ) |
| static

Escapes any of the characters having special meaning for wxRegEx.

Currently the following characters are special: \, ^, $, ., |, ?, *, +, (, ), [, ], { and }. All occurrences of any of these characters in the passed string are escaped, i.e. a backslash is inserted before them, to remove their special meaning.

For example:

wxString quoted = wxRegEx::QuoteMeta("foo.*bar");
assert( quoted == R"(foo\.\*bar)" );
wxRegEx::QuoteMeta
static wxString QuoteMeta(const wxString &str)
Escapes any of the characters having special meaning for wxRegEx.

This function can be useful when using wxRegEx to search for a literal string entered by user, for example.

Parameters

  str | A string that may contain metacharacters to escape.

Returns
  A string with all metacharacters escaped.

Since
  3.1.3

## ◆ Replace()

int wxRegEx::Replace | ( | wxString * | text,
|  | const wxString & | replacement,
|  | size_t | maxMatches = 0 ) const

Replaces the current regular expression in the string pointed to by text, with the text in replacement and return number of matches replaced (maybe 0 if none found) or -1 on error.

The replacement text may contain back references `\number` which will be replaced with the value of the corresponding subexpression in the pattern match. `\0` corresponds to the entire match and `&` is a synonym for it. Backslash may be used to quote itself or `&` character.

maxMatches may be used to limit the number of replacements made, setting it to 1, for example, will only replace first occurrence (if any) of the pattern in the text while default value of 0 means replace all.

## ◆ ReplaceAll()

int wxRegEx::ReplaceAll | ( | wxString * | text,
|  | const wxString & | replacement ) const

Replace all occurrences: this is actually a synonym for Replace().

See also
  ReplaceFirst()

## ◆ ReplaceFirst()

int wxRegEx::ReplaceFirst | ( | wxString * | text,
|  | const wxString & | replacement ) const

Replace the first occurrence.