例如:
- thisIsMySample
应该:
- this_Is_My_Sample
我的代码:
- System.Text.RegularExpressions.Regex.Replace(input,"([A-Z])","_$0",System.Text.RegularExpressions.RegexOptions.Compiled);
它工作正常,但如果输入更改为:
- ThisIsMySample
输出将为:
- _This_Is_My_Sample
如何忽略第一次发生?
解决方法
非正则表达式解决方案
- string result = string.Concat(input.Select((x,i) => i > 0 && char.IsUpper(x) ? "_" + x.ToString() : x.ToString()));
似乎也很快:正则表达式:2569ms,C#:1489ms
- Stopwatch stp = new Stopwatch();
- stp.Start();
- for (int i = 0; i < 1000000; i++)
- {
- string input = "ThisIsMySample";
- string result = System.Text.RegularExpressions.Regex.Replace(input,"(?<=.)([A-Z])",System.Text.RegularExpressions.RegexOptions.Compiled);
- }
- stp.Stop();
- MessageBox.Show(stp.ElapsedMilliseconds.ToString());
- // Result 2569ms
- Stopwatch stp2 = new Stopwatch();
- stp2.Start();
- for (int i = 0; i < 1000000; i++)
- {
- string input = "ThisIsMySample";
- string result = string.Concat(input.Select((x,j) => j > 0 && char.IsUpper(x) ? "_" + x.ToString() : x.ToString()));
- }
- stp2.Stop();
- MessageBox.Show(stp2.ElapsedMilliseconds.ToString());
- // Result: 1489ms