我正在为IRC protocol abnf message format编写正则表达式。 以下是我写的一些正则表达式的一个简短例子。如何编写代码中的正则表达式
// digit = %x30-39 ; 0-9
// "[0-9]"
static const std::string digit("[\x30-\x39]");
我用前面的定义,以形成更复杂的,这会非常复杂,速度快。当我有问题,特别是更复杂的正则表达式时,将它们组成:
// hexdigit = digit/"A"/"B"/"C"/"D"/"E"/"F"
// "[[0-9]ABCDEF]"
static const std::string hexdigit("[" + digit + "ABCDEF]");
A“hexdigit”是“数字”或“六角信”。
注意:我不在乎RFC将“hexdigit”字母(ABCDEF)定义为只是大写字母。我只是按照RFC的说法行事,我不打算改变他们的要求。
const std::regex digit(dapps::regex::digit);
assert(std::regex_match("0", digit));
assert(std::regex_match("1", digit));
assert(std::regex_match("2", digit));
assert(std::regex_match("3", digit));
assert(std::regex_match("4", digit));
assert(std::regex_match("5", digit));
assert(std::regex_match("6", digit));
assert(std::regex_match("7", digit));
assert(std::regex_match("8", digit));
assert(std::regex_match("9", digit));
assert(!std::regex_match("10", digit));
在上面的代码中,匹配“数字”工作方式的目的是在ABNF。
然而, “hexdigit” 现在是非法的正则表达式语法:
[[0-9]ABCDEF]
比
[0-9ABCDEF]
相反,并试图以配合它不会工作:
const std::regex hexdigit(dapps::regex::hexdigit);
assert(std::regex_match("0", hexdigit));
assert(std::regex_match("1", hexdigit));
assert(std::regex_match("2", hexdigit));
assert(std::regex_match("3", hexdigit));
assert(std::regex_match("4", hexdigit));
assert(std::regex_match("5", hexdigit));
assert(std::regex_match("6", hexdigit));
assert(std::regex_match("7", hexdigit));
assert(std::regex_match("8", hexdigit));
assert(std::regex_match("9", hexdigit));
assert(std::regex_match("A", hexdigit));
assert(std::regex_match("B", hexdigit));
assert(std::regex_match("C", hexdigit));
assert(std::regex_match("D", hexdigit));
assert(std::regex_match("E", hexdigit));
assert(std::regex_match("F", hexdigit));
assert(!std::regex_match("10", hexdigit));
结果,如果我让“数字”没有“范围选择器中的单个字符”,([ ]
),那么你不能se“数字”以匹配“数字”。
我可能只是完全错误的方式,所以我的问题是: 我是否真的需要保留两个版本,一个有或没有括号,或者有一个更简单的方法来组成正则表达式。
如果我正确地读你,你想捕捉十六进制数? – Saleem
十六进制数字是被捕获的20个其他组成正则表达式之一,是的。但问题不在于捕获十六进制数字,而在于从更简单的复杂正则表达式组成复杂正则表达式。 –
创建一个将保存“0-9”或“ABCDEF”的字符类类。实现一个方法来加入另一个字符类对象。实现一个返回正则表达式的类(在本例中添加括号)。然后你可以做一些像'std :: regex_match(“B”,digits.or(a_to_f).regexp())'。 – Amadan