【问题标题】:Why doesn't the icase flag for regex work correctly [duplicate]为什么正则表达式的icase标志不能正常工作[重复]
【发布时间】:2020-07-13 07:43:10
【问题描述】:

这个函数应该返回字符串中元音的第一个实例,但它只适用于小写。我认为regex_constants::icase 也应该处理大写字母。另外,请随时提出更好的方法来做到这一点。

以下内容为“HAPPY”返回 0(现在返回 -1),为“GREaT”返回 3:

#include <regex>

int firstVowel(std::string str)
{
    std::smatch match;
    std::regex pattern("[aeiou]", std::regex_constants::icase);
    while (std::regex_search(str, match, pattern))
    {
        return match.position();
    }
    return -1;
}

我通过 main 获得回报:

std::cout << firstVowel("HAPPY") << "\n";
std::cout << firstVowel("GREaT") << "\n";

【问题讨论】:

  • 一个简单的方法是"[aAeEiIoOuU]"。另外,请使用if,而不是while。看来that works
  • @WiktorStribiżew 知道为什么这段代码不起作用(我也测试了if)吗?
  • 你可能正在使用一个“糟糕”的编译器,它的 std::regex 实现很差。
  • 我正在使用 clang 编译,HAPPY 生成 1 作为返回值,2 生成 GREaT
  • 我正在使用 Visual Studio。我应该使用其他东西吗?

标签: c++ regex match


【解决方案1】:

请不要使用该库 icase:C++11 regex::icase inconsistent behavior 太可怕了……

而是像这样将字符串切换为小写:

std::string data = "Abc";
std::transform(data.begin(), data.end(), data.begin(),
[](unsigned char c){ return std::tolower(c); });

如果您使用非标准 ASCII 字符而不是自己使用,则希腊字母、中文字符、罗马尼亚字母等没有从大到小的顺序....

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2014-06-26
  • 1970-01-01
  • 2013-11-05
  • 2020-04-26
  • 1970-01-01
  • 2011-05-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多