【问题标题】:Match any lowercase/uppercase chained character and add an additional one匹配任何小写/大写链接字符并添加一个附加字符
【发布时间】:2021-07-09 02:22:52
【问题描述】:

在 Javascript 中,我想做以下事情。 当我匹配一个小写字母后跟一个大写字母时,我想在它之间添加一个特殊字符。

前:

  • myHouse => my_House
  • aRandomString => a_Random_String

等等……

我为这场比赛做了一个正则表达式 =>

/([a-z][A-Z](.{0}))+/g

我遇到的问题是如果我这样做了

"aRandomString".replace(/([a-z][A-Z](.{0}))+/g, '_')

当然可以 => _ando_tring

编辑:

我做了这个,但是这不是太复杂了吗?

var mString = "aRandomString";
var match = mString.match(/([a-z][A-Z](.{0}))+/g, '_')
var save = [...match]
match = match.map(e => [e.slice(0, 1), '_', e.slice(1)].join(''))
save.forEach((s,i) => mString = mString.replace(s, match[i]))
console.log(mString)

【问题讨论】:

  • str.replace(/[A-Z]/g, letter => `_${letter}`
  • @Bobby ...当亨利选择它作为示例代码时,aTestStringForMULTIPLEUpperCase 这样的字符串值会发生什么?有人期望..._MULTIPLEUpper_Case,这将是任何与您的任务完全匹配的解决方案的结果,还是有人期望..._MULTIPLE_Upper_Case 更符合逻辑?
  • hiw 版本还可以,我需要的只是一个_,当有低位后跟高位时。不管它是否切词或任何东西。

标签: javascript regex typescript


【解决方案1】:

是的。您可以轻松地仅匹配您正在寻找的小写、大写模式并替换为replacer

const mString = "aTestStringForMULTIPLEUpperCase";
const uString = mString.replace(/[a-z][A-Z]/g, v => `${v[0]}_${v[1]}`);
console.log(uString);

【讨论】:

    【解决方案2】:

    一个more robust/generic approach,它考虑了一个额外的大写边界(不仅是小写后面跟着大写,而且还有一个位于另一个左上和右下之间的上)可能看起来像这样......

    const regXUppecaseBoundaries = (/(?:(?<=[a-z])[A-Z])|(?:(?<=[A-Z])[A-Z](?=[a-z]))/g);
    
    const sampleText = `myHouse aRandomString
    aRandomString aTestStringForMULTIPLEUpperCase
    myHouse AaAAaTestStringForMULTIPLEUpperCase`;
    
    // also check ... [https://regex101.com/r/OpmSbx/1]
    console.log(
      sampleText.replace(regXUppecaseBoundaries, '_$&')
    );
    .as-console-wrapper { min-height: 100%!important; top: 0; }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-08
      • 1970-01-01
      • 2022-06-12
      • 1970-01-01
      • 2013-05-03
      • 2014-09-07
      • 2015-07-07
      相关资源
      最近更新 更多