正则表达式截取字符串的方法技巧
有这么一段字符串:
[数字]字符串
结果
取 a=数字
b=字符串
截取方法1:
inta=Convert.ToInt32(txt1.Text.Trim().Replace('[',']').Split(']')[1]);
stringb=txt1.Text.Trim().Replace('[',']').Split(']')[2];
截取方法2:
stringstr="[数字]字符串"; Regexreg=newRegex(@" ([^]+)\](.*)"); stringa=Convert.ToInt32(reg.Match(str).Groups[1].Value); stringb=Convert.ToInt32(reg.Match(str).Groups[2].Value);
截取方法3
stringtempStr="[数字]字符串"; stringpattern=@" ([\s§]∗) ([\s\S]*)"; Regexre=newRegex(pattern); stringstr1=Regex.Replace(tempStr,pattern,"$1"); stringstr2=Regex.Replace(tempStr,pattern,"$2");
变成数组怎么写
///<summary>
///返回一个字符串数组
///</summary>
///<paramname="str"></param>
///<returns></returns>
publicstring[]ReturnIDAndName(stringstr)
{
string[]stringArray=newstring[2];
Regexreg=newRegex(@"
([^]+)\](.*)");
stringArray[0]=reg.Match(str).Groups[1].Value;
stringArray[1]=reg.Match(str).Groups[2].Value;
returnstringArray;
}
///<summary>
///截取字符串编号
///</summary>
publicintReturnId(stringstr)
{
try
{
if(string.IsNullOrEmpty(str))
{
return0;
}
Regexregex=newRegex("(?<=\\[)\\d+(?=\\])");
Matchm=regex.Match(str);
intpid;
if(!m.Success)
{
pid=int.Parse("["+regex.Match(str).Value+"]");
}
returnint.Parse(regex.Match(str).Value);
}
catch
{
return0;
}
}
以上就是本文给大家分享的正则表达式截取字符串的方法技巧,希望大家喜欢。
热门推荐
10 跨年简短祝福语学生毕业
11 新年酒席开席祝福语简短
12 乘风语文考试祝福语简短
13 疫情五一快乐祝福语简短
14 祝愿新生宝宝祝福语简短
15 舞蹈老师晚安祝福语简短
16 娶嫂子的祝福语简短
17 外婆祝福语短句唯美简短
18 校长退休文案祝福语简短