首页 新闻 赞助 找找看

C# 正则表达式替换

0
悬赏园豆:50 [已解决问题] 解决于 2012-10-16 08:37

我需要将

字符串 类似:KX024-A0145bb03-cc08

替换为:KX024-A0145bb-cc

字符串中的03和08是流水号,也就是说我想去除该字符串中的流水号

请帮忙指导一下

问题补充:

补充一下,除了流水号 是两位,其他字符长度不定,"-"是分隔符

skyzsx的主页 skyzsx | 初学一级 | 园豆:35
提问于:2012-10-13 16:03
< >
分享
最佳答案
0

要是您的字符串固定格式可以定义为:

"<若干数字或字母>-<若干数字或字母><两位流水号>-<若干数字或字母><两位流水号>"

<若干数字或字母>,在正则里写成,可以是0个或多个:[a-zA-Z0-9]*

<两位流水号>,这里我假设它只会是数字,不会是字母:[0-9]{2}

这样的话,正则可以这样写:

@"^([a-zA-Z0-9]*-[a-zA-Z0-9]*?)[0-9]{2}(-[a-zA-Z0-9]*?)[0-9]{2}$"

然后就可以替换了:

Regex.Replace("your string", @"^([a-zA-Z0-9]*-[a-zA-Z0-9]*?)[0-9]{2}(-[a-zA-Z0-9]*?)[0-9]{2}$", "$1$2");

收获园豆:35
miuq | 菜鸟二级 |园豆:237 | 2012-10-13 16:36
其他回答(2)
0
public string DoReg(string Inputstr)
        {
            string str = Inputstr;
            Regex reg = new Regex("[\\d]{2}");
            Match mat = reg.Match(str);
            List<string> list = new List<string>();
            if (mat.Success)
            {
                MatchCollection mc = reg.Matches(str);
                int temp = 0;
                for (int i = 0; i < mc.Count; i++)
                {
                    int index = mc[i].Index - temp * 2;
                    if (index > 0)
                    {
                        if (str[index - 1] >= '0' && str[index - 1] <= '9')
                            continue;
                    }
                    if (index < str.Length - 2)
                    {
                        if (str[index + 2] >= '0' && str[index + 2] <= '9')
                            continue;
                    }
                    str = str.Substring(0, index) + str.Substring(index + 2);
                    temp++;
                }
            }
            return str;
        }
收获园豆:5
田林九村 | 园豆:2367 (老鸟四级) | 2012-10-13 16:59
0

Regex.Replace(xx,@"(\S+)\w{2}(-\w+)\w{2}","$1$2");

收获园豆:10
向往-SONG | 园豆:4853 (老鸟四级) | 2012-10-13 20:26
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册