服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - 正则表达式 - 正则表达式截取字符串的方法技巧

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

2020-08-15 19:54正则之家 正则表达式

这篇文章主要介绍了正则表达式截取字符串的方法技巧,需要的朋友可以参考下

有这么一段字符串:

[数字]字符串

结果

取  a=数字

     b=字符串

截取方法1:

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

截取方法2:

?
1
2
3
4
5
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

?
1
2
3
4
5
6
7
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");

 

  变成数组怎么写

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
  /// <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;
    }
  }

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

延伸 · 阅读

精彩推荐