[英]Trying to get a regex to recognize and extract words from both camelCase and CamelCase
我已經中途工作了。 這非常有效:
'MyOwnVar'.match(/([a-z]*)([A-Z][a-z]+)/g)
結果:
["My", "Own", "Var"]
目標是拉出單詞。 但是如果我將camelCase名稱傳遞給它:
'myOwnVar'.match(/([a-z]*)([A-Z][a-z]+)/g)
我明白了:
["myOwn", "Var"]
我無法弄清楚我做錯了什么。 據我所知,兩組()
應該將匹配結果存儲在兩個獨立的數組元素中。 出於某種原因,它們將它們混為一談。
如果我已正確理解了這個問題,那么下面的正則表達式應該可以解決問題:
/([A-Za-z][a-z]+)/g
如果單個字符(“mOwnVariable”中的“m”)應被視為單詞 :
/([A-Za-z][a-z]*)/g
您可以使用
/([A-Z]?[a-z]+)/g
請參閱正則表達式說明https://regex101.com/r/zS8vJ3/1
// For camelCase var matches = 'myOwnVar'.match(/([AZ]?[az]+)/g); document.write('// For camelCase<pre>' + JSON.stringify(matches, 0, 2) + '</pre>'); // For CamelCase var matches = 'MyOwnVar'.match(/([AZ]?[az]+)/g); document.write('<hr /> // For CamelCase <pre>' + JSON.stringify(matches, 0, 2) + '</pre>');
問題是用()
分組不會將不同的組存儲在不同的數組元素中。 與(ab)(cd)
匹配將始終與(abcd)
相同。
現在除非情況比你讓它更復雜,否則只需/([AZ]*[az]+)/g
。
var result = 'MyOwnVar'.match(/([AZ]*[az]+)/g); document.getElementById('one').innerHTML = result.join(); result = 'myOwnVar'.match(/([AZ]*[az]+)/g); document.getElementById('two').innerHTML = result.join();
<div id="one"></div> <div id="two"></div>
對於其他情況,例如HTMLContent
輸入,請參閱其他答案。
試試這個:
'MyOwnVar'.match(/([a-z]+)|([A-Z][a-z]+)/g)
'myOwnVar'.match(/([a-z]+)|([A-Z][a-z]+)/g)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.