正则表达式截取字符串的方法技巧
更新时间:2015年09月22日 10:53:41 投稿:mrr
这篇文章主要介绍了正则表达式截取字符串的方法技巧,需要的朋友可以参考下
有这么一段字符串:
[数字]字符串
结果
取 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; } }
以上就是本文给大家分享的正则表达式截取字符串的方法技巧,希望大家喜欢。
相关文章
使用正则表达式过滤 S3 上以 _$folder$ 结尾的占位文件的方法
当我们使用命令行批量从 S3 上拷贝文件或统计文件数量时,希望能排除掉 S3 上以 _$folder$ 结尾的占位文件,这个正则表达式应该怎么写呢,本文给大家介绍使用正则表达式过滤 S3 上以 _$folder$ 结尾的占位文件的方法,感兴趣的朋友一起看看吧2023-12-12解读邮箱正则表达式:^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$
这篇文章主要介绍了解读邮箱正则表达式:^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$,需要的朋友可以参考下2020-02-02Python中正则表达式match()、search()函数及match()和search()的区别详解
这篇文章主要介绍了Python中正则表达式match()、search()函数及match()和search()的区别详解的相关资料,需要的朋友可以参考下2015-09-09
最新评论