在c++中将字符串解析为未知数量的正则表达式组
Parse string into and unknown amount of regex groups in C++
我知道我应该得到的文本的确切格式。特别是,它应该匹配具有可变数量组的正则表达式。
我想使用c++ regex库来确定(a)如果它是有效的文本,(b)将这些组解析成一个向量。我该怎么做呢?我可以在网上找到做(a)的例子,但找不到(b)。
#include <string>
#include <regex>
#include <vector>
bool parse_this_text(std::string & text, std::vector<std::string> & group) {
// std::string text_regex = "^([a-z]*)(,[0-9]+)*$"
// if the text matches the regex, return true and parse each group into the vector
// else return false
???
}
使得下面的代码行返回预期的结果。
std::vector<std::string> group;
parse_this_text("green,1", group);
// should return true with group = {"green", ",1"};
parse_this_text("yellow", group);
// should return true with group = {"yellow"};
parse_this_text("red,1,2,3", group);
// should return true with group = {"red", ",1", ",2", ",3"};
parse_this_text("blue,1.0,3.0,1,a", group);
// should return false (since it doesn't match the regex)
谢谢!
(?=^([a-zA-Z]*)(?:,d+)+$)^.*?(?:((?:,d+)+)).*?$
你可以用这个。这将首先使用向前看验证,然后返回2组。
1)包含名称
2)包含所有其余的整数(这可以很容易地分割),或者您可以在这里使用re.findall
虽然它不能完全回答你的问题,但它可能会有所帮助。
看一看。
http://regex101.com/r/wE3dU7/3一种选择是扫描字符串两次,第一次检查其有效性,第二次将其拆分为字段。在OP的例子中,一旦你知道它是正确的,你就不需要regexen来分割线;你可以简单地用逗号分开。但是为了说明起见,您可以使用std::regex_token_iterator
(假设您有支持这些的c++库),如下所示:
bool parse_this_text(const std::string& s, std::vector<std::string>& result) {
static const std::regex check("[[:alpha:]][[:alnum:]]*(,[[:digit:]])*",
std::regex_constants::nosubs);
static const std::regex split(",");
if (!std::regex_match(s, check))
return false;
std::sregex_token_iterator tokens(s.begin(), s.end(), split, -1);
result.clear();
std::copy(tokens, std::sregex_token_iterator(), std::back_inserter(result));
return true;
}
对于更复杂的情况,或者不需要双重扫描的应用程序,您可以使用连续调用std::regex_search()
进行标记,将前一次匹配的结束作为起点,并将std::regex_constants::continuous
作为匹配标志;这将在前一次匹配之后将每次搜索锚定到字符。在这种情况下,您可以使用std::regex_iterator
,但我不相信结果代码会更简单。
相关文章:
- 使用正则表达式regex_search在字符串中查找字符串
- 在 C++ 中使用正则表达式错误时出现问题 括号表达式中的范围无效
- C++正则表达式无限循环
- FindPackageHandleStandardArgs.cmake:137 的 CMake 错误(消息):找不到 Boost (缺少:正则表达式)(找到合适的版本"1.72.0",
- 定义有趣的宏和正则表达式在Z3 C++绑定
- 带有多个字符分隔符的正则表达式
- C++ 使用增强正则表达式库时断言崩溃
- 有人可以帮助我处理正则表达式吗?
- 使用正则表达式获取大括号块的列表
- 正则表达式以匹配数字的重复模式,后跟任何类型的分隔符?
- 组合正则表达式部分使用 | 不起作用的 C++
- 为什么C++正则表达式这么慢?
- 如何使HTML5电子邮件验证正则表达式在C++中工作?
- 在C++中实现正则表达式
- C++正则表达式替换整个单词
- 用C++编写正则表达式的正确方法是什么?
- 如何从Stroustrup的C++书中解释这个正则表达式?
- 为什么这个正则表达式C++在括号表达式中抛出无效范围异常?
- C++:匹配正则表达式,什么是匹配?
- C++:正则表达式匹配代码,打印多个匹配项?