正则表达式截取字符串的方法技巧

发布时间:2019-08-06 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了正则表达式截取字符串的方法技巧脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

有这么一段字符串:

[数字]字符串

结果

取  a=数字

     b=字符串

截取方法1:

 int a = Convert.ToInt32(txt1.Text.Trim().Replace('[', ']').SplIT(']')[1]);    string b = txt1.Text.Trim().Replace('[', ']').Split(']')[2]; 

截取方法2:

 string str = "[数字]字符串"; Regex reg = new Regex(@" ([^]+)/](.*)"); string a= Convert.ToInt32( reg.Match(str).Groups[1].Value); string b= Convert.ToInt32( reg.Match(str).Groups[2].Value);

截取方法3

 string tempStr = "[数字]字符串";  string pattern = @" ([/s§]∗) ([/s/S]*)"; Regex re = new Regex(pattern);  string str1 = Regex.Replace(tempStr,pattern,"$1");  string str2 = Regex.Replace(tempStr, pattern, "$2");

  变成数组怎么写

   /// <summary>   /// 返回一个字符串数组   /// </summary>   /// <param name="str"></param>   /// <returns></returns>   public string[] ReturnIDAndName(string str)   {         string[] stringArray = new string[2];         Regex reg = new Regex(@" ([^]+)/](.*)");     stringArray[0]= reg.Match(str).Groups[1].Value;     stringArray[1] = reg.Match(str).Groups[2].Value;         return stringArray;   }      /// <summary>   /// 截取字符串编号   /// </summary>   public int ReturnId(string str)   {     try     {       if (string.IsNullOrEmpty(str))       {         return 0;       }       Regex regex = new Regex("(?<=//[)//d+(?=//])");       Match m = regex.Match(str);       int pid;       if (!m.Success)       {         pid = int.Parse("[" + regex.Match(str).Value + "]");       }       return int.Parse(regex.Match(str).Value);     }     catch     {       return 0;     }   }

脚本宝典总结

以上是脚本宝典为你收集整理的正则表达式截取字符串的方法技巧全部内容,希望文章能够帮你解决正则表达式截取字符串的方法技巧所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。