简体   繁体   English

如何拆分包含数字的驼峰式字符串

[英]How to split a camel case string containing numbers

I have camel cased strings like this:我有这样的驼峰字符串:

"numberOf40"
"numberOf40hc"

How can I split it like this?我怎么能这样拆分它?

["number", "Of", "40"]
["number", "Of", "40hc"]

I am using humps to decamelize keys so I can only pass a split regex as option.我正在使用驼峰对键进行 decamelize,因此我只能将split正则表达式作为选项传递。 I am looking for an answer that only uses split function.我正在寻找仅使用split function 的答案。

My best attempts:我最好的尝试:

const a = "numberOf40hc"

a.split(/(?=[A-Z0-9])/)
// ["number", "Of", "4", "0hc"]

a.split(/(?=[A-Z])|[^0-9](?=[0-9])/)
// ["number", "O", "40hc"]

Also I don't understand why the f is omitted in my last attempt.另外我不明白为什么在我最后一次尝试中省略了f

You don't get the f in you last attempt (?=[AZ])|[^0-9](?=[0-9]) as this part of the last pattern [^0-9] matches a single char other than a digit and will split on that char.你最后一次尝试中没有得到f (?=[AZ])|[^0-9](?=[0-9])因为最后一个模式[^0-9]的这一部分匹配一个字符而不是数字,并将在该字符上拆分。

You could also match instead of split您也可以匹配而不是拆分

 const regex = /[AZ]?[az]+|\d+[az]*/g; [ "numberOf40", "numberOf40hc" ].forEach(s => console.log(Array.from(s.matchAll(regex), m => m[0])));

Using split only, you could use lookarounds with a lookbehind which is gaining more browser support.仅使用拆分,您可以使用带有后视功能的环视,这将获得更多浏览器支持。

 const regex = /(?=[AZ])|(?<=[az])(?=\d)/g; [ "numberOf40", "numberOf40hc" ].forEach(s => console.log(s.split(regex)));

 const a = "numberOf40hc" let b = a.split(/(\d+[az]*|[AZ][az]*)/).filter(a => a); console.log(b);

The .filter(a => a) is necessary because split , returns both the left and right side of a matched delimter. .filter(a => a)是必要的,因为split返回匹配分隔符的左侧和右侧。 Eg 'a.'.split('.') returns both the left (ie 'a' ) and right (ie '' ) side of '.'例如'a.'.split('.')返回 '.' 的左侧(即'a' )和右侧(即'''.' . .

Per your update regarding the need for compatibility with humps , it seems humps supports customizing the handler:根据您关于需要与humps兼容的更新, humps似乎支持自定义处理程序:

const humps = require('humps');

let myObj = {numberOf40hc: 'value'};

let decamelizedObj = humps.decamelizeKeys(myObj, key =>
        key.split(/(\d+[a-z]*|[A-Z][a-z]*)/).filter(a => a).join('_'));

console.log(decamelizedObj);

Try this:尝试这个:

 const splitStr = (str='') => str.split(/([AZ][az]+)/).filter(e => e); console.log( splitStr("numberOf40") ); console.log( splitStr("numberOf40hc") );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM