C#替换字符串里特定的字符为对应数组中的值|获取字符串中的数字|替换字符串数字在数组中的值
说明:string s = "123213[img2]234324[img1]sadsa[img4]d[imgasdsa]asdasd[img3].....";
string[] alts = {"0","|1|","|2|","|3|","|4|",......};
把字符串“[img"+数字+"]”这一段字符串替换为数组 对应 数字 元素的值。
private void button1_Click(object sender, EventArgs e)
{
string s = "123213[img2]234324[img1]sadsa[img4]d[imgasdsa]asdasd[img3]";
string[] alts = {"0","|1|","|2|","|3|","|4|"};
System.Text.RegularExpressions.MatchCollection sR = System.Text.RegularExpressions.Regex.Matches(s, @"\[img[1-9]+[0-9]*\]", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.StringBuilder strR = new System.Text.StringBuilder();
int i = 0;
foreach (System.Text.RegularExpressions.Match m in sR)
{
i = GetNumberInt(m.Value);
if(i>0)
{
s = s.Replace(m.Value,alts[i]);
}
}
richTextBox1.Text=s;
}
public static int GetNumberInt(string str)
{
int result = 0;
if (str != null && str != string.Empty)
{
// 正则表达式剔除非数字字符(不包含小数点.)
str = System.Text.RegularExpressions.Regex.Replace(str, @"[^\d.\d]", "");
// 如果是数字,则转换为decimal类型
if (System.Text.RegularExpressions.Regex.IsMatch(str, @"^[+-]?\d*[.]?\d*$"))
{
result = int.Parse(str);
}
}
return result;
}
相关文章
评论列表(0) 订阅
暂无评论
禁止评论