与正则表达式代码作斗争:CamelCase to camel_case

Guy*_*gal 0 c# regex

我能够将字符串转换MyClassNamemy_class_name使用正则表达式

但是我的解决方案不起作用MyOtherTClassName,应该转换为my_other_t_class_name.

另外,这也不起作用ClassNumber1,应该将其转换为class_number_1

没有进入我的解决方案,这还不够好,我想帮助转换正则表达式代码:

  1. MyClassName -> my_class_name
  2. MyOtherTClassName -> my_other_t_class_name
  3. MyClassWith1Number -> my_class_with_1_number

谢谢,

盖伊

Bas*_*i M 6

背后的逻辑是您希望将每个大写字母转换为其小写变体,并在它(以及每个数字)前面加上下划线。
例如 aT变成_t6变成_6
唯一的例外是第一个字符。你不想在它之前有一个undersoce。正则表达式将使用负向后视处理这种情况,以便不匹配第一个字符。

//using System.Text.RegularExpression

//your input
string input = "MyOtherTClass1Name";

//the regex
string result = Regex.Replace(
    input, 
    "((?<!^)[A-Z0-9])", //the regex, see below for explanation
    delegate(Match m) { return "_" + m.ToString().ToLower(); }, //replace function
    RegexOptions.None
);
result = result.ToLower(); //one more time ToLower(); for the first character of the input

Console.WriteLine(result);
Run Code Online (Sandbox Code Playgroud)

对于正则表达式本身:

(           #start of capturing group
  (?<!      #negative lookbehind
     ^      #beginning of the string
  )         #end of lookbehind
  [A-Z0-9]  #one of A-Z or 0-9
)           #end of capturing group
Run Code Online (Sandbox Code Playgroud)

所以我们捕获每一个大写字母和每一个数字(除了第一个字符),并用一个小写的变体和前面的下划线来替换它们。