有条件地忽略 c++11 正则表达式中的大小写
Conditionally ignore case in c++11 regular expressions
我正在尝试编写一个函数,该函数将允许用户指定是否要在正则表达式匹配中忽略大小写。 我想出了一个解决方案,但它非常笨拙。有没有办法在构建正则表达式时有条件地设置 std::regex_constants::icase
标志?
#include <string>
#include <regex>
std::string sub(std::string string, std::string match, bool ic){
std::regex r;
std::regex rc(match, std::regex_constants::collate);
std::regex ric(match, std::regex_constants::icase | std::regex_constants::collate);
if(ic){
r = ric;
} else {
r = rc;
}
std::smatch matches;
if(std::regex_search(string,matches, r)){
return matches[0];
} else {
return "no match";
}
}
有很多方法可以有条件地设置标志。例如,使用条件运算符:
std::regex r(match, ic ? std::regex_constants::icase | std::regex_constants::collate
: std::regex_constants::collate);
在这种情况下,
为了提高可读性,我更喜欢好的旧if
:
auto flags = std::regex_constants::collate;
if(ic) flags |= std::regex_constants::icase;
std::regex r(match, flags);
此代码也比带有条件运算符 ?
的版本更容易维护。请考虑将来要添加另一个条件标志。这很简单,只需添加另一行if
:
if(ns) flags |= std::regex_constants::nosubs;
尝试使用条件运算符执行此操作,代码将迅速降级为意大利面条。
相关文章:
- 使用正则表达式regex_search在字符串中查找字符串
- 在 C++ 中使用正则表达式错误时出现问题 括号表达式中的范围无效
- C++正则表达式无限循环
- FindPackageHandleStandardArgs.cmake:137 的 CMake 错误(消息):找不到 Boost (缺少:正则表达式)(找到合适的版本"1.72.0",
- 定义有趣的宏和正则表达式在Z3 C++绑定
- 带有多个字符分隔符的正则表达式
- C++ 使用增强正则表达式库时断言崩溃
- 有人可以帮助我处理正则表达式吗?
- 使用正则表达式获取大括号块的列表
- 正则表达式以匹配数字的重复模式,后跟任何类型的分隔符?
- 组合正则表达式部分使用 | 不起作用的 C++
- 为什么C++正则表达式这么慢?
- 如何使HTML5电子邮件验证正则表达式在C++中工作?
- 在C++中实现正则表达式
- C++正则表达式替换整个单词
- 用C++编写正则表达式的正确方法是什么?
- 如何从Stroustrup的C++书中解释这个正则表达式?
- 如何提升Perl正则表达式匹配,支持区分大小写/不区分大小写
- 有条件地忽略 c++11 正则表达式中的大小写
- c++切换正则表达式大小写