加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 正则表达式骆驼案以下划线.忽略第一次发生

发布时间:2020-12-15 06:23:08 所属栏目:百科 来源:网络整理
导读:例如: thisIsMySample 应该: this_Is_My_Sample 我的代码: System.Text.RegularExpressions.Regex.Replace(input,"([A-Z])","_$0",System.Text.RegularExpressions.RegexOptions.Compiled); 它工作正常,但如果输入更改为: ThisIsMySample 输出将为: _Th
例如:
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读