正则表达式分裂骆驼案 [英] Regex to split camel case

查看:166
本文介绍了正则表达式分裂骆驼案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JavaScript中有一个正则表达式,使用以下代码将我的驼峰字符串字符串拆分为大写字母(我后来从 here ):

I have a regular expression in JavaScript to split my camel case string at the upper-case letters using the following code (which I subsequently got from here):

"MyCamelCaseString"
    .replace(/([A-Z])/g, ' $1')
    .replace(/^./, function(str){ return str.toUpperCase(); })

因此返回:

"My Camel Case String"

这很好。但是,我想把它提升一个档次。有人可以用一个正则表达式来帮助我,只有当前一个字符是小写且后者是大写时才会分裂。

Which is good. However, I want to step this up a notch. Could someone help me with a regex which will split if, and only if, the former character is lower-case and the latter is upper-case.

因此,以上示例将是我期望的结果,但如果我这样做:

Thus, the above example will be the result I expect, but if I do:

"ExampleID"

然后我回来了:

"Example ID"

而不是

"Example I D"

因为它在每个大写字母中分裂并忽略它之前的任何内容。

Since it's splitting at each upper-case and ignoring anything before it.

希望这有意义!谢谢:)。

Hope that makes sense! And thanks :).

推荐答案

我的猜测是替换 /([AZ])/ /([az])([AZ])/ '$ 1''$ 1 $ 2'

My guess is replacing /([A-Z])/ with /([a-z])([A-Z])/ and ' $1' with '$1 $2'

"MyCamelCaseString"
    .replace(/([a-z])([A-Z])/g, '$1 $2');

/([a-z0-9])([AZ]) / 用于计算小写字符的数字

/([a-z0-9])([A-Z])/ for numbers counting as lowercase characters

console.log("MyCamelCaseStringID".replace(/([a-z0-9])([A-Z])/g, '$1 $2'))

这篇关于正则表达式分裂骆驼案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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