简体   繁体   中英

How to collate sequence \" using ECMAScript regular expressions?

I'm trying to construct a regular expression to treat delimited speech marks ( \\" ) as a single character.

The following code compiles fine, but terminates on trying to initialise rgx, throwing the error Abort trap: 6 using libc++.

std::regex rgx("[[.\\\\\".]]");
std::smatch results;
std::string test_str("\\\"");
std::regex_search(test_str, results, rgx);

If I remove the [[. .]] [[. .]] , it runs fine, results[0] returning \\" as intended, but as said, I'd like for this sequence to be usable as a character class.

Edit: Ok, I realise now that my previous understanding of collated sequences was incorrect, and the reason it wouldn't work is that \\\\\\\\\\" is not defined as a sequence. So my new question: is it possible to define collated sequences?

So I figured out where I was going wrong and thought I'd leave this here in case anyone stumbles across it.

You can specify a passive group of characters with (?:sequence) , allowing quantifiers to be applied as with a character class. Perhaps not exactly what I'd originally asked, but fulfils the same purpose, in my case at least.

To match a string beginning and ending with double quotation marks (including these characters in the results), but allowing delimited quotation marks within the the string, I used the expression

\"(?:[^\"^\\\\]+|(?:\\\\\\\\)+|\\\\\")*\"

which says to grab the as many characters as possible, provided characters are not quotation marks or backslashes, then if this does not match, to firstly attempt to match an even number of backslashes (to allow delimiting of this character), or secondly a delimited quotation mark. This non-capturing group is matched as many times as possible, stopping only when it reaches a \\" .

I couldn't comment on the efficiency of this, but it definitely works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM