'-6ren">
gpt4 book ai didi

regex - 将 CamelCase 字符串转换为带下划线的大写

转载 作者:行者123 更新时间:2023-12-01 09:06:57 24 4
gpt4 key购买 nike

我有一个字符串“CamelCase”,我使用这个 RegEx :

string pattern = "(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])";          
string[] substrings = Regex.Split("CamelCase", pattern);

substring 中,我有 Camel 和 Case,那是找到的,但我想要所有的 uppercase 就像这个 CAMEL 和 CASE。更好的是,我想要一个像这样的 CAMEL_CASE 字符串,但是用 Regex 来代替 ALL

最佳答案

这是一个 JavaScript 实现。

function camelCaseToUpperCase(str) {
return str.replace(/([a-z])([A-Z])/, '$1_$2').toUpperCase();
}

演示

printList([ 'CamelCase', 'camelCase' ],
function(value, idx, values) {
return value + ' -> '
+ camelCaseToUpperCase(value) + ' -> '
+ camelToTitle(value, '_');
}
);

// Case Conversion Functions
function camelCaseToUpperCase(str) {
return str.replace(/([a-z])([A-Z])/, '$1_$2').toUpperCase();
}
function camelToTitle(str, delimiter) {
return str.replace(/([A-Z][a-z]+)/g, ' $1') // Words beginning with UC
.replace(/([A-Z][A-Z]+)/g, ' $1') // "Words" of only UC
.replace(/([^A-Za-z ]+)/g, ' $1') // "Words" of non-letters
.trim() // Remove any leading/trailing spaces
.replace(/[ ]/g, delimiter || ' '); // Replace all spaces with the delim
}

// Utility Functions
function printList(items, conversionFn) {
var str = '<ul>';
[].forEach.call(items, function(item, index) {
str += '<li>' + conversionFn(item, index, items) + '</li>';
});
print(str + '</ul>');
}
function print() {
write.apply(undefined, arguments);
}
function println() {
write.apply(undefined, [].splice.call(arguments,0).concat('<br />'));
}
function write() {
document.getElementById('output').innerHTML += arguments.length > 1 ?
[].join.call(arguments, ' ') : arguments[0]
}
#output {
font-family: monospace;
}
<h1>Case Conversion Demo</h1>
<div id="output"></div>

关于regex - 将 CamelCase 字符串转换为带下划线的大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11959637/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com