【问题标题】:Regular Expression: Convert a numeric string from camelCase to regular正则表达式:将数字字符串从 camelCase 转换为正则
【发布时间】:2015-09-21 06:15:48
【问题描述】:

我需要将一个字母数字字符串转换为普通字符串,它是用驼峰式命名的。我的输入可以是以下任何字符串:

var strs = {
    input: [
        "thisStringIsGood",
        "somethingLikeThis",
        "a123CapsHere345AndHEREButNOT678Here90End",
        "123CapsHere345AndHEREButNOT678Here90e",
        "ABCAcryonym",
        "xmlHTTPRequest",
    "thisDeviceHasA3PrintingService"
    ],
    expectedResult: [
        "This String Is Good",
        "Something Like This",
        "A123 Caps Here345 And HERE But NOT678 Here90 End",
        "123 Caps Here345 And HERE But NOT678 Here90 e",
        "ABC Acryoynm",
        "Xml HTTP Request",
    "This Device Has A3 Printing Service"
    ]
};

在将字符串转换为预期的格式之后,我正在这样做:

function capSplit(str) {
        return str.replace(/(^[a-z]+)|[0-9]+|[A-Z][a-z]+|[A-Z]+(?=[A-Z][a-z]|[0-9])/g, function (match, first) {
            if (first) match = match[0].toUpperCase() + match.substr(1);
            return match + ' ';
        })
    }

但问题是空格也添加了数字。我需要将字符串"thisDeviceHasA3Service" 转换为"This Device Has A3 Printing Service" 但函数capSplit(str) 给了我This Device Has A 3 Printing Service 我不知道我缺少什么。这是fiddle

【问题讨论】:

  • 为什么"e""123 Caps Here345 And HERE But NOT678 Here90 e", 不大写?

标签: javascript regex


【解决方案1】:

这是我找到的解决方案:

function capSplit(str) {
  return str.replace(/([A-Z][a-z])|([a-z][A-Z])|(\d[a-zA-Z])/g, function (g, m1, m2, m3) {
    return m1 ? " " + m1 : (m2 ? m2[0] + " " + m2[1] : m3[0] + " " + m3[1]);
  }).replace(/^[a-z]/g, function (g) {
    return g.toUpperCase();
  });
}

主正则表达式匹配需要插入空格的每种情况,然后函数在需要的地方插入空格

【讨论】:

    【解决方案2】:

    你可以从这里https://stackoverflow.com/a/6229124/915194使用稍微改变的函数

    function capSplit(str) {
        return str
        // insert a space between lower & upper
        .replace(/([a-z])([A-Z])/g, '$1 $2')
        // insert a space between number & any letter
        .replace(/([0-9])([A-Za-z])/g, '$1 $2')
        // space before last upper in a sequence followed by lower
        .replace(/\b([A-Z]+)([A-Z])([a-z])/, '$1 $2$3')
        // uppercase the first character
        .replace(/^./, function(str){ return str.toUpperCase(); })
    }
    

    【讨论】:

    • 为什么?我用你的fiddle 测试了它。看起来所有结果都对应于 expectedResult 数组。
    • 它转换字符串 a123CapsHere345AndHEREButNOT678Here90End-->A 123 Caps Here 345 And HERE But NOT 678 Here 90 End。 A123 转换为 A 123
    【解决方案3】:

    答案是,在前瞻中松开|[0-9],你的代码就可以工作了

    function capSplit(str) {
            return str.replace(/(^[a-z]+)|[0-9]+|[A-Z][a-z]+|[A-Z]+(?=[A-Z][a-z])/g, function (match, first) {
                if (first) match = match[0].toUpperCase() + match.substr(1);
                return match + ' ';
            })
        }
    

    这里是更新的 jsfiddle link

    【讨论】:

      猜你喜欢
      • 2015-09-09
      • 2012-01-28
      • 2022-11-18
      • 2011-09-28
      • 2016-12-03
      • 2013-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多