如何在C#.net中使用正则表达式替换组值 [英] how to replace group value using regex in c# .net

查看:22
本文介绍了如何在C#.net中使用正则表达式替换组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的字符串

  string s =我于1978年12月出生于美国."; 

现在,我想使用正则表达式将 12月 转换为 12月

我在下面使用了不完整的正则表达式

  s = Regex.Replace(s,(1月| 2月| 3月| 4月| 5月| 6月| 7月| 8月| 9月| 10月| 11月| 12月),CultreInfo.InvariantCulture.TextInfo.ToTitleCase(?????),RegexOption.IgnoreCase); 

我在这里必须写些什么(?????),这样我才能得到低于输出的值

  s =我于1978年12月在美国出生."; 

还有其他可以应用的方式吗?

解决方案

查看

I have a string like

string s= "I WAS born in AMERICA on december 1978.";

Now I want to convert december to December using regex

I have used below incomplete regex

s=Regex.Replace(s,(january|february|march|April|may|june|july|august|september|October|november|December),CultreInfo.InvariantCulture.TextInfo.ToTitleCase(?????),RegexOption.IgnoreCase);

What I have to write here (?????) so that I can get below output

s= "I WAS born in AMERICA on December 1978.";

Is there any other way which I can apply??

解决方案

Looking at regex.replace documentation, I notice that you'd have to use a callback function.

So write a function:

function CustomReplace( Match m ) {
    return CultreInfo.InvariantCulture.TextInfo.ToTitleCase(m.Groups[1].Value)
}

and pass it as the 3rd argument:

s = Regex.Replace(
    s,
    "(january|february|march|April|may|june|july|august|september|October|november|December)",
    CustomReplace,
    RegexOption.IgnoreCase
);

这篇关于如何在C#.net中使用正则表达式替换组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆