• 企业400电话
  • 微网小程序
  • AI电话机器人
  • 电商代运营
  • 全 部 栏 目

    企业400电话 网络优化推广 AI电话机器人 呼叫中心 网站建设 商标✡知产 微网小程序 电商运营 彩铃•短信 增值拓展业务
    正则表达式截取字符串的方法技巧

    有这么一段字符串:

    [数字]字符串

    结果

    取  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;
        }
      }

    以上就是本文给大家分享的正则表达式截取字符串的方法技巧,希望大家喜欢。

    您可能感兴趣的文章:
    • 正则表达式匹配不包含某些字符串的技巧
    • 使用正则表达式找出不包含特定字符串的条目
    • JS正则表达式提取字符串中所有汉字的脚本
    • 利用正则表达式将字符串分组示例代码
    上一篇:php正则表达式完全教程之精华篇
    下一篇:匹配 IP 地址与域名的正则表达式
  • 相关文章
  • 

    © 2016-2020 巨人网络通讯

    时间:9:00-21:00 (节假日不休)

    地址:江苏信息产业基地11号楼四层

    《增值电信业务经营许可证》 苏B2-20120278

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