代码之家  ›  专栏  ›  技术社区  ›  Sturm

增强regex捕获组并替换

  •  0
  • Sturm  · 技术社区  · 6 年前

    我尝试用以下方式展开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”变成了“expandamelase lease”,出了点问题。

    我怀疑我没有抓到我应该抓到的人。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Michał Turczyn    6 年前

    简单使用 (?<=[a-z])(?=[A-Z])

    它使用lookback (?<=[a-z]) ,看后面是不是小写字母,看前面是不是( (?=[A-Z])

    那就用空格代替 .

    Demo

        2
  •  1
  •   Nambi_0915    6 年前

    试试这个,

    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