【问题标题】:Why doesn't std::regex_match return true with $ pattern?为什么 std::regex_match 不使用 $ 模式返回 true?
【发布时间】:2017-03-04 11:14:34
【问题描述】:

std::regex_replace,
我可以使用“$”匹配单词的结尾,然后附加其他字符。

std::cout << std::regex_replace("word",std::regex("$"),"s") << '\n';
//prints: words

由于结果与原始输入不同,我假设正则表达式匹配。

然而,

std::cout << std::boolalpha;
std::cout << std::regex_match("word",std::regex("$")) << '\n';
//prints: false

怎么会是正则表达式不匹配,而regex_replace却能进行替换?


我还尝试为 0 个或更多字符添加 *,但这引发了异常:

  std::cout << std::regex_match("word",std::regex("*$")) << '\n';
  std::cout << std::regex_replace("word",std::regex("*$"),"s") << '\n';

【问题讨论】:

    标签: c++ regex exception string-matching


    【解决方案1】:

    请注意,regex_match 只会成功地将正则表达式匹配到整个字符序列,而 std::regex_search 将成功匹配子序列。

    您需要regex_search 来匹配子序列。 $ 不匹配整个非空字符串,但匹配非空字符串的(零长度)子字符串。

    【讨论】:

      猜你喜欢
      • 2015-02-08
      • 2023-02-16
      • 2022-01-25
      • 1970-01-01
      • 2013-07-21
      • 2021-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多