前端之家收集整理的这篇文章主要介绍了
正则表达式 - 双引号内字符转星号/单词首字母转大写,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;//引用
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnChange_Click(object sender,EventArgs e)
{
//首字母大写
//rtbResult.Text = Regex.Replace(rtbSource.Text,@"\w+",new MatchEvaluator(CapText));
//双引号内其他字符转星号
rtbResult.Text = Regex.Replace(rtbSource.Text,"\"[^\"]*\"",new MatchEvaluator(XingHao));
}
//将单词的首字母转为大写(注:此处引用自 http://msdn.microsoft.com/zh-cn/library/cft8645c(v=vs.80).aspx)
//如:【may i help you】 转为:【May I Help You】
static string CapText(Match m)
{
// Get the matched string.
string x = m.ToString();
// If the first char is lower case...
if (char.IsLower(x[0]))
{
// Capitalize it.
return char.ToUpper(x[0]) + x.Substring(1,x.Length - 1);
}
return x;
}
//将双引号中的字符转为星号*
//如:【"what" can "i" do for you"】 转为:【"****" can "*" do for you"】
static string XingHao(Match m) //本人仍觉此算法略显粗糙,有较好算法者望指教一二
{
StringBuilder strBld = new StringBuilder();
string x = m.ToString();
for (int i = 0; i < x.Length - 2;i++ )
{
strBld.Append("*");
}
return x.Substring(0,1) + strBld.ToString() + x.Substring(x.Length-1);
}
}
}