hello 'this' is my'str'ing
正則表達式爲大寫沒有用單引號
包圍如果我有串這樣的,我想,使其全部大寫,如果沒有單引號包圍。
hello 'this' is my'str'ing
=>HELLO 'this' IS MY'str'ING
有一個簡單的方法,我可以在節點實現這也許使用正則表達式?
hello 'this' is my'str'ing
正則表達式爲大寫沒有用單引號
包圍如果我有串這樣的,我想,使其全部大寫,如果沒有單引號包圍。
hello 'this' is my'str'ing
=>HELLO 'this' IS MY'str'ING
有一個簡單的方法,我可以在節點實現這也許使用正則表達式?
您可以使用下面的正則表達式:
'[^']+'|(\w)
這是一個活生生的例子:
var subject = "hello 'this' is my'str'ing";
var regex = /'[^']+'|(\w)/g;
replaced = subject.replace(regex, function(m, group1) {
if (!group1) {
return m;
}
else {
return m.toUpperCase();
}
});
document.write(replaced);
這個答案的幸得zx81
。欲瞭解更多信息,請參閱zx81
的original answer。
由於JavaScript不支持lookbehinds,我們不得不使用它匹配任何一個單詞邊界不匹配\B
。
在這種情況下,\B'
確保'
不在\w
([a-zA-Z0-9_]
)中的任何內容的右側。同樣,'\B
對左側進行了類似的檢查。
(?:(.*?)(?=\B'.*?'\B)(?:(\B'.*?'\B))|(.*?)$)
(regex demo)
使用回調函數,並檢查,以查看是否捕獲1或3的長度是> 0,並且如果它是,該匹配
**樣品返回一個大寫使用\U
和\L
只是大寫和小寫的相關匹配。您的回調不必曾經影響$2
的情況下,讓‘亞當’可以保持‘亞當’等
無關,而是一張紙條給任何人誰可能會嘗試這樣做反向。這是給此相反的要容易得多:
(\B'.+?'\B)
regex demo
也許你正在尋找http://stackoverflow.com/questions/5166862/javascript-regular-expression-iterator-to-extract-組 – paddy
您需要解析器。 –
匹配'([^'] +)('[^'] *')?'然後使用_function()_回調加入組1的上部。 – sln