我如何使用regex_replace
How do I use regex_replace?
在SO上问这个问题后,我意识到我需要用另一个字符串替换字符串中的所有匹配。在我的情况下,我想用' s*'替换空格的所有出现(即。任何数量的空格都可以匹配)。
所以我设计了如下:
#include <string>
#include <regex>
int main ()
{
const std::string someString = "here is some text";
const std::string output = std::regex_replace(someString.c_str(), std::regex("\s+"), "\s*");
}
失败,输出如下:
错误:没有匹配的函数调用' regex_replace(const char*, std::regex, const char [4])
工作示例:http://ideone.com/yEpgXy
不要气馁,我前往cplusplus.com,发现我的尝试实际上匹配regex_replace
函数的第一个原型很好,所以我很惊讶编译器不能运行它(供您参考:http://www.cplusplus.com/reference/regex/match_replace/)
所以我想我就运行他们为这个函数提供的例子:
// regex_replace example
#include <iostream>
#include <string>
#include <regex>
#include <iterator>
int main ()
{
std::string s ("there is a subsequence in the stringn");
std::regex e ("\b(sub)([^ ]*)"); // matches words beginning by "sub"
// using string/c-string (3) version:
std::cout << std::regex_replace (s,e,"sub-$2");
// using range/c-string (6) version:
std::string result;
std::regex_replace (std::back_inserter(result), s.begin(), s.end(), e, "$2");
std::cout << result;
// with flags:
std::cout << std::regex_replace (s,e,"$1 and $2",std::regex_constants::format_no_copy);
std::cout << std::endl;
return 0;
}
但是当我运行这个,我得到完全相同的错误!
工作示例:http://ideone.com/yEpgXy
所以ideone.com或cplusplus.com都是错误的。与其把脑袋撞到墙上去诊断那些比我聪明得多的人的错误,我不如省下我的理智,问你。
你需要更新你的编译器到GCC 4.9
尝试使用boost regex作为替代
regex_replace
简单代码c++ regex_replace only字母数字字符
#include <iostream>
#include <regex>
using namespace std;
int main() {
const std::regex pattern("[^a-zA-Z0-9.-_]");
std::string String = "!#!e-ma.il@boomer.zx";
// std::regex_constants::icase
// Only first
// std::string newtext = std::regex_replace( String, pattern, "X", std::regex_constants::format_first_only );
// All case insensitive
std::string newtext = std::regex_replace( String, pattern, "", std::regex_constants::icase);
std::cout << newtext << std::endl;
return 0;
}
运行https://ideone.com/CoMq3r
相关文章:
- 此模式的C++RegEx
- C++ std::regex 使用前瞻失败
- std::regex:匹配由数字和空格组成的字符串,并提取数字.如何?
- 使用 boost::regex 从目录中获取带有一些正则表达式的文件名称时出现意外输出
- 你能防止 std::regex 在无效表达式上抛出异常吗?
- 如何使用字符串::replace方法写入文件
- 使用Regex解析cpp中的字符串并创建映射
- C++:如何用split查找单词?Regex
- 在VC2015U3上,std::regex比boost::regex慢得多
- 是否有更有效的方法来生成日期的REGEX字符串
- 在C++中使用带有regex的捕获组
- 将std::regex设置为静态的好主意吗
- 为什么Regex(c++)需要指数时间
- std::regex and dual ABI
- C++11 std::regex后备选项
- 以不同的方式替换每一项,regex c++
- 使用 boost::regex (c++) 比较两个正则表达式
- 如何在插入排序中使用 replace() 使语句变得不必要
- Build Boost Regex for Windows VS2013
- CMake中的奇怪字符串(REGEX REPLACE)行为