您现在的位置是:网站首页> 编程资料编程资料
正则表达式截取字符串的方法技巧_正则表达式_
2023-05-25
256人已围观
简介 正则表达式截取字符串的方法技巧_正则表达式_
有这么一段字符串:
[数字]字符串
结果
取 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");
变成数组怎么写
////// 返回一个字符串数组 /// /// ///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; } /// /// 截取字符串编号 /// 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; } }
以上就是本文给大家分享的正则表达式截取字符串的方法技巧,希望大家喜欢。
相关内容
- php正则表达式完全教程之精华篇_正则表达式_
- PHP正则表达式完全教程之提高篇_正则表达式_
- PHP正则表达式完全教程之基础篇_正则表达式_
- JS正则表达式基本用法(经典全)_正则表达式_
- Email正则表达式日常整理大全_正则表达式_
- 正则表达式匹配,替换,查找_正则表达式_
- 详解PHP正则表达式替换实现(PHP preg_replace,PHP preg_replace)_正则表达式_
- 收集一些常用的正则表达式(匹配中文字符、匹配双字节字符、匹配HTML标记、匹配空行 and so on~~~)_正则表达式_
- javascript中使用正则表达式删除前后空格的方法_正则表达式_
- JavaScript中的正则表达式使用及验证qq号码的正则_正则表达式_
