当前位置:Gxlcms > 正则表达式 > 正则表达式截取字符串的方法技巧

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

时间:2021-07-01 10:21:17 帮助过:110人阅读

有这么一段字符串:

[数字]字符串

结果

取  a=数字

     b=字符串

截取方法1:

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

截取方法2:

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

截取方法3

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

  变成数组怎么写

  1. /// <summary>
  2. /// 返回一个字符串数组
  3. /// </summary>
  4. /// <param name="str"></param>
  5. /// <returns></returns>
  6. public string[] ReturnIDAndName(string str)
  7. {
  8. string[] stringArray = new string[2];
  9. Regex reg = new Regex(@"
  10. ([^]+)\](.*)");
  11. stringArray[0]= reg.Match(str).Groups[1].Value;
  12. stringArray[1] = reg.Match(str).Groups[2].Value;
  13. return stringArray;
  14. }
  15. /// <summary>
  16. /// 截取字符串编号
  17. /// </summary>
  18. public int ReturnId(string str)
  19. {
  20. try
  21. {
  22. if (string.IsNullOrEmpty(str))
  23. {
  24. return 0;
  25. }
  26. Regex regex = new Regex("(?<=\\[)\\d+(?=\\])");
  27. Match m = regex.Match(str);
  28. int pid;
  29. if (!m.Success)
  30. {
  31. pid = int.Parse("[" + regex.Match(str).Value + "]");
  32. }
  33. return int.Parse(regex.Match(str).Value);
  34. }
  35. catch
  36. {
  37. return 0;
  38. }
  39. }

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

人气教程排行