付小贝
付小贝

Reputation: 3

Is this a bug of boost regex?

I wanna match any chars like a-z,A-Z,0-9,and -, so I wrote this:

#include "thirdparty/boost/regex.hpp"
#include <iostream>


using namespace std;

int main(){
    string reg = "[a-z-A-Z0-9]";
    boost::regex expression(reg);
    cout<<"OK"<<endl;
}

when running, program core dumped and says:

terminate called after throwing an instance of 'boost::exception_detail::clone_impl >' what(): Invalid range end in character class The error occurred while parsing the regular expression: '[a-z->>>HERE>>>A-Z0-9]'.

who can tell me why?

Upvotes: 0

Views: 1018

Answers (1)

hwnd
hwnd

Reputation: 70750

The cause of this is the hyphen (-) after the first range inside your character class. Inside of a character class the hyphen has special meaning. You can place the hyphen as the first or last character of the class.

[-a-zA-Z0-9]
[a-zA-Z0-9-]

In some regular expression implementations, you can also place directly after a range.

If you place the hyphen anywhere else you need to escape it in order to add it to your class.

Actual regular expression implementation:

[a-z\-A-Z0-9]

As a string literal:

string reg = "[a-z\\-A-Z0-9]";

Upvotes: 6

Related Questions