【问题标题】:boost regex capture group and replace提升正则表达式捕获组并替换
【发布时间】:2019-02-22 07:53:37
【问题描述】:

我正在尝试以这种方式扩展 CamelCase 字符串:CamelCase >> Camel Case,使用 boost。

string Utils::ExpandCamelCase(string & str)
{
    static boost::regex camelCaseExpandRegex = boost::regex(R"(\B[A-Z]+?(?=[A-Z][^A-Z])|\B[A-Z]+?(?=[^A-Z]))");
    string result = boost::regex_replace(str, camelCaseExpandRegex, "  $1");
    return result;
}

如您所见,我正在尝试捕获第一组,它应该是每个单词的大写字母(不包括第一个),并将其替换为空格加上该组。

出现问题,因为“ExpandCamelCasePlease”变成了“Expand amel ase lease”。

尝试变体我怀疑我没有按我应该的方式捕获该组。

我需要进行哪些更改才能正确扩展大写字母前的驼峰式大小写插入空格?

【问题讨论】:

标签: c++ regex boost


【解决方案1】:

只需使用(?<=[a-z])(?=[A-Z])

它使用lookbehind (?<=[a-z]),看后面是否是小写字母,它向前看((?=[A-Z]))看前面是否是大写字母。

然后将其替换为空格

Demo

【讨论】:

    【解决方案2】:

    试试这个,

    string Utils::ExpandCamelCase(string & str)
    {
    static boost::regex camelCaseExpandRegex = boost::regex(R"([A-Z][^ ]+?)(?=[A-Z]|$)");
    string result = boost::regex_replace(str, camelCaseExpandRegex, "  $1");
    return result;
    

    }

    Regex

    【讨论】:

      猜你喜欢
      • 2011-09-02
      • 2014-05-28
      • 1970-01-01
      • 2014-06-19
      • 2010-11-19
      • 2019-01-27
      • 1970-01-01
      • 2013-06-27
      • 2014-08-30
      相关资源
      最近更新 更多