有条件地忽略 c++11 正则表达式中的大小写

Conditionally ignore case in c++11 regular expressions

本文关键字:大小写 正则表达式 c++11 有条件      更新时间:2023-10-16

我正在尝试编写一个函数,该函数将允许用户指定是否要在正则表达式匹配中忽略大小写。 我想出了一个解决方案,但它非常笨拙。有没有办法在构建正则表达式时有条件地设置 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;

尝试使用条件运算符执行此操作,代码将迅速降级为意大利面条。