Trying to get a regular expression for recognizing and extracting words from both camelCase and CamelCase

It works for me halfway. This works great:

'MyOwnVar'.match(/([a-z]*)([A-Z][a-z]+)/g)

Result:

["My", "Own", "Var"]

The goal is to pull out individual words. But if I give it the name camelCase:

'MyOwnVar'.match(/([a-z]*)([A-Z][a-z]+)/g)

I get:

["myOwn", "Var"]

I cannot understand what I am doing wrong. As far as I can tell, two sets ()should store the matching results in two separate elements of the array. For some reason, they bring them together.

+4
source share
4 answers

If I understood the question correctly, the following regex should do the trick:

/([A-Za-z][a-z]+)/g

In case one character (like "m" in "mOwnVariable") should be considered as a word:

/([A-Za-z][a-z]*)/g
+7

/([A-Z]?[a-z]+)/g

. regex https://regex101.com/r/zS8vJ3/1

// For camelCase
var matches = 'myOwnVar'.match(/([A-Z]?[a-z]+)/g);
document.write('// For camelCase<pre>' + JSON.stringify(matches, 0, 2) + '</pre>');


// For CamelCase
var matches = 'MyOwnVar'.match(/([A-Z]?[a-z]+)/g);
document.write('<hr /> // For CamelCase <pre>' + JSON.stringify(matches, 0, 2) + '</pre>');
Hide result
+1

, () . (ab)(cd) , (abcd).

, , , /([A-Z]*[a-z]+)/g .

var result = 'MyOwnVar'.match(/([A-Z]*[a-z]+)/g);
document.getElementById('one').innerHTML = result.join();

result = 'myOwnVar'.match(/([A-Z]*[a-z]+)/g);
document.getElementById('two').innerHTML = result.join();
<div id="one"></div>
<div id="two"></div>
Hide result

, HTMLContent, . ().

+1

:

    'MyOwnVar'.match(/([a-z]+)|([A-Z][a-z]+)/g)

    'myOwnVar'.match(/([a-z]+)|([A-Z][a-z]+)/g)
0

Source: https://habr.com/ru/post/1611065/


All Articles