Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to get a regex to recognize and extract words from both camelCase and CamelCase

I've got this halfway working. This works great:

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

Result:

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

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

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

I get:

["myOwn", "Var"]

I can't figure out what I'm doing wrong. As far as I can tell, two sets of () should store the matching results in two separate array elements. It's lumping them in together for some reason.

like image 461
ffxsam Avatar asked Jan 07 '23 09:01

ffxsam


2 Answers

If I have understood the question properly the following regex should do the trick:

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

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

/([A-Za-z][a-z]*)/g
like image 87
undefined Avatar answered Jan 26 '23 08:01

undefined


You can use

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

See regex explanation 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>');
like image 27
Tushar Avatar answered Jan 26 '23 08:01

Tushar