使用正则表达式拆分camelCase字符串

时间:2020-12-27 21:45:26

I have a Camel case string like this s = 'ThisIsASampleString' and I want to split into an array using the capital letters as the delimiting point. I am expecting this:

我有一个类似于这个s ='ThisIsASampleString'的Camel案例字符串,我想使用大写字母作为分隔点拆分成一个数组。我期待这个:

['This', 'Is', 'A', 'Sample', 'String']

Here is what I have done so far

这是我到目前为止所做的

s = "ThisIsASampleString";
var regex = new RegExp('[A-Z]',"g");
var arr = s.split(re);

But this is not giving me the correct result because it removes the matched character. I am getting this array as my result ["his", "s", "", "tring"]. It has removed all the matched capital letters.

但这并没有给我正确的结果,因为它删除了匹配的字符。我得到这个数组作为我的结果[“他的”,“s”,“”,“tring”]。它删除了所有匹配的大写字母。

How should I avoid this behavior and keep the matched characters also in my result array?

我应该如何避免这种行为并将匹配的字符保留在我的结果数组中?

1 个解决方案

#1


6  

Your regex would split based on the uppercase but the result array doesn't include the matched value. Instead use positive look-ahead assertion to assert the position.

您的正则表达式将基于大写分割,但结果数组不包括匹配的值。而是使用积极的前瞻断言来断言这个位置。

s = "ThisIsASampleString";
var arr = s.split(/(?=[A-Z])/);

console.log(arr);

Regex explanation here

正则表达式在这里解释


Or you can use String#match method instead.

或者您可以使用String#match方法代替。

s = "ThisIsASampleString";
var arr = s.match(/[A-Z][^A-Z]*/g);

console.log(arr);

Regex explanation here

正则表达式在这里解释

#1


6  

Your regex would split based on the uppercase but the result array doesn't include the matched value. Instead use positive look-ahead assertion to assert the position.

您的正则表达式将基于大写分割,但结果数组不包括匹配的值。而是使用积极的前瞻断言来断言这个位置。

s = "ThisIsASampleString";
var arr = s.split(/(?=[A-Z])/);

console.log(arr);

Regex explanation here

正则表达式在这里解释


Or you can use String#match method instead.

或者您可以使用String#match方法代替。

s = "ThisIsASampleString";
var arr = s.match(/[A-Z][^A-Z]*/g);

console.log(arr);

Regex explanation here

正则表达式在这里解释