Thread overview
regex: ] in a character class
Dec 12, 2020
kdevel
Dec 12, 2020
Tobias Pankrath
Dec 12, 2020
Tobias Pankrath
December 12, 2020
In some situations a ] must be escaped as in

   auto re = regex(`^[a\]]$`); // match a and ] only

Unfortunately dmd/phobos does not warn if you forget the backslash:

   auto re = regex(`^[a]]$`); // match a]

This leads me to the documentation [1] which says

   \c where c is one of [|*+?() 	Matches the character c itself.

] must be added to this list since \] obviously matches ]. Additionally
the statement

   any character except [{|*+?()^$     Matches the character itself.

is not true since ] does not match itself when ] denotes the end of
a character class. I don't have a suggestion for better wording yet.

[1] https://dlang.org/phobos/std_regex.html
December 12, 2020
On Saturday, 12 December 2020 at 12:03:49 UTC, kdevel wrote:
> In some situations a ] must be escaped as in
>
>    auto re = regex(`^[a\]]$`); // match a and ] only
>
> Unfortunately dmd/phobos does not warn if you forget the backslash:
>
>    auto re = regex(`^[a]]$`); // match a]
>
> This leads me to the documentation [1] which says
>
>    \c where c is one of [|*+?() 	Matches the character c itself.
>
> ] must be added to this list since \] obviously matches ]. Additionally
> the statement
>
>    any character except [{|*+?()^$     Matches the character itself.
>
> is not true since ] does not match itself when ] denotes the end of
> a character class. I don't have a suggestion for better wording yet.
>
> [1] https://dlang.org/phobos/std_regex.html

As I understand it, the statement is indeed true and a regex `]]]` would match and only match the string `]]]`. What should be added somewhere is

>   Inside character classes the character ']' has to be written as '\]'.
December 12, 2020
On Saturday, 12 December 2020 at 12:03:49 UTC, kdevel wrote:
> I don't have a suggestion for better wording yet.
>
> [1] https://dlang.org/phobos/std_regex.html

This [1] is how I would word it.

[1] https://github.com/dlang/phobos/pull/7724