我想将 std::string
拆分为 regex
。
我在 Stackoverflow 上找到了一些解决方案,但其中大多数是按单个空格分割字符串或使用诸如 boost 之类的外部库。
我不能使用升压。
我想通过正则表达式拆分字符串 - "\\s+"
。
我正在使用这个 g++ 版本 g++ (Debian 4.4.5-8) 4.4.5
我无法升级。
原文由 nothing-special-here 发布,翻译遵循 CC BY-SA 4.0 许可协议
我想将 std::string
拆分为 regex
。
我在 Stackoverflow 上找到了一些解决方案,但其中大多数是按单个空格分割字符串或使用诸如 boost 之类的外部库。
我不能使用升压。
我想通过正则表达式拆分字符串 - "\\s+"
。
我正在使用这个 g++ 版本 g++ (Debian 4.4.5-8) 4.4.5
我无法升级。
原文由 nothing-special-here 发布,翻译遵循 CC BY-SA 4.0 许可协议
为了扩展@Pete Becker 的答案,我提供了一个 resplit 函数示例,可用于使用正则表达式拆分文本:
#include <regex>
std::vector<std::string> resplit(const std::string &s, const std::regex &sep_regex = std::regex{"\\s+"}) {
std::sregex_token_iterator iter(s.begin(), s.end(), sep_regex, -1);
std::sregex_token_iterator end;
return {iter, end};
}
这工作如下:
string s1 = "first second third ";
vector<string> v22 = resplit(s1);
for (const auto & e: v22) {
cout <<"Token:" << e << endl;
}
//Token:first
//Token:second
//Token:third
string s222 = "first|second:third,forth";
vector<string> v222 = resplit(s222, "[|:,]");
for (const auto & e: v222) {
cout <<"Token:" << e << endl;
}
//Token:first
//Token:second
//Token:third
//Token:forth
原文由 Marcin 发布,翻译遵循 CC BY-SA 4.0 许可协议
3 回答2k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
2 回答3.2k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
1 回答2.7k 阅读✓ 已解决
3 回答3.4k 阅读
1 回答2.7k 阅读✓ 已解决
如果您只想将字符串拆分为多个空格,则不需要使用正则表达式。编写自己的正则表达式库对于这么简单的事情来说太过分了。
您在评论中链接到的答案 是在 C++ 中拆分字符串? , 可以很容易地更改,以便在有多个空格时不包含任何空元素。
通过检查
item.length() > 0
在推动item
到elems
向量之前,如果您的输入包含多个分隔符(空格)