std :: regex,以匹配字符串的开始/结束 [英] std::regex, to match begin/end of string

查看:446
本文介绍了std :: regex,以匹配字符串的开始/结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JS正则表达式中,符号 ^ $ 指定字符串的开始和结束。而且只有使用 / m 修饰符(多行模式),它们才能匹配行首和行尾-CR / LF之前和之后的位置。

In JS regular expressions symbols ^ and $ designate start and end of the string. And only with /m modifier (multiline mode) they match start and end of line - position before and after CR/LF.

但在 std :: regex / ECMAscript模式符号 ^ $ 始终匹配行首和行尾

But in std::regex/ECMAscript mode symbols ^ and $ match start and end of line always.

std :: regex中是否可以定义字符串的开始和结束匹配点?换句话说:为了支持JavaScript多行模式...

Is there any way in std::regex to define start and end of the string match points? In other words: to support JavaScript multiline mode ...

推荐答案

默认情况下,ECMAscript模式已经处理了 ^ 作为输入的开始行的开始, $ 都作为输入的结束输入行尾。没有办法使它们仅与输入 的开头或结尾匹配,但是可以使它们仅与 的开头或结尾匹配:

By default, ECMAscript mode already treats ^ as both beginning-of-input and beginning-of-line, and $ as both end-of-input and end-of-line. There is no way to make them match only beginning or end-of-input, but it is possible to make them match only beginning or end-of-line:

调用 std :: regex_match std :: regex_search std :: regex_replace ,其中有一个类型为 std :: regex_constants :: match_flag_type 默认为 std :: regex_constants :: match_default


  • 要指定 ^ 仅与行首匹配,请指定 std :: regex_constants :: match_not_bol

  • 要指定 $ 仅匹配行尾,指定 std :: regex_constants :: match_not_eol

  • 由于这些值是位标志,因此要指定两者,只需按位或将它们一起指定( std :: regex_constants :: match_not_bol | std :: regex_constants :: match_not_eol

  • 请注意,无需使用 ^ 并通过指定 std :: regex_constants :: match_continuous 来确定是否存在 std :: regex_constants :: match_not_bol

  • To specify that ^ matches only beginning-of-line, specify std::regex_constants::match_not_bol
  • To specify that $ matches only end-of-line, specify std::regex_constants::match_not_eol
  • As these values are bitflags, to specify both, simply bitwise-or them together (std::regex_constants::match_not_bol | std::regex_constants::match_not_eol)
  • Note that beginning-of-input can be implied without using ^ and regardless of the presence of std::regex_constants::match_not_bol by specifying std::regex_constants::match_continuous

ECMAScript语法文档 cppreference.com

注意:我已经使用MSVC,Clang + libc ++和Clang + libstdc ++进行了测试,只有MSVC在以下位置具有正确的行为礼物。

Caveat: I've tested with MSVC, Clang + libc++, and Clang + libstdc++, and only MSVC has the correct behavior at present.

这篇关于std :: regex,以匹配字符串的开始/结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆