正则表达式截取字符串的方法技巧
2019/6/29 21:03:13
本文主要是介绍正则表达式截取字符串的方法技巧,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
有这么一段字符串:
[数字]字符串
结果
取 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; } }
以上就是本文给大家分享的正则表达式截取字符串的方法技巧,希望大家喜欢。
这篇关于正则表达式截取字符串的方法技巧的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-01-0939. 干货系列从零用Rust编写负载均衡及代理,正则及格式替换
- 2024-01-08如何编写高效的正则表达式?
- 2023-12-29"Matlab中的正则表达式:强大而灵活的工具"
- 2023-09-30这个正则 为啥同样的单号第二个就提取不出来?
- 2023-06-086.2 re 正则表达式
- 2023-06-06将字符串里的\x01,\x02这些替换掉用正则表达式无效?
- 2023-05-24正则表达式详解
- 2023-05-17我让gpt写了一段正则表达式代码,可是运行报错,可以帮忙看看哪里出了问题?
- 2023-04-27我要提取text4文本中的邮箱号 正则应该怎么写?
- 2023-04-15bash shell 无法使用 perl 正则