SoFunction
Updated on 2025-03-01

Tips for intercepting strings with regular expressions

There is such a string:

[number] string

result

Take a=number

b=String

Intercept method 1:

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

Intercept method 2:

string str = "[number] string";
Regex reg = new Regex(@"
([^]+)\](.*)");
string a= Convert.ToInt32( (str).Groups[1].Value);
string b= Convert.ToInt32( (str).Groups[2].Value);

Intercept method 3

string tempStr = "[number] string"; 
string pattern = @"
([\s§]∗)
([\s\S]*)";
Regex re = new Regex(pattern); 
string str1 = (tempStr,pattern,"$1"); 
string str2 = (tempStr, pattern, "$2");

How to write an array

  /// <summary>
  /// Return an array of strings  /// </summary>
  /// <param name="str"></param>
  /// <returns></returns>
  public string[] ReturnIDAndName(string str)
  {    
    string[] stringArray = new string[2];    
    Regex reg = new Regex(@"
([^]+)\](.*)");
    stringArray[0]= (str).Groups[1].Value;
    stringArray[1] = (str).Groups[2].Value;    
    return stringArray;
  } 
 
  /// <summary>
  /// Intercept the string number  /// </summary>
  public int ReturnId(string str)
  {
    try
    {
      if ((str))
      {
        return 0;
      }
      Regex regex = new Regex("(?<=\\[)\\d+(?=\\])");
      Match m = (str);
      int pid;
      if (!)
      {
        pid = ("[" + (str).Value + "]");
      }
      return ((str).Value);
    }
    catch
    {
      return 0;
    }
  }

The above are the techniques and techniques for intercepting strings of regular expressions shared with you in this article. I hope you like it.