在c++中将字符串解析为未知数量的正则表达式组

Parse string into and unknown amount of regex groups in C++

本文关键字:未知数 正则表达式 c++ 字符串      更新时间:2023-10-16

我知道我应该得到的文本的确切格式。特别是,它应该匹配具有可变数量组的正则表达式。

我想使用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,但我不相信结果代码会更简单。