lia*_*dee 3 c# parsing html-parsing
如何确定字符串开头的数字(任意位数)?
一些可能的字符串
1123|http://example.com
2|daas
Run Code Online (Sandbox Code Playgroud)
哪个应该返回1123和2.
使用正则表达式:
using System.Text.RegularExpressions;
str = "35|http:\/\/v10.lscache3.c.youtube.com\/videoplayback...";
Regex r = new Regex(@"^[0-9]{1,2}");
Match m = r.Match(str);
if(m.Success) {
Console.WriteLine("Matched: " + m.Value);
} else {
Console.WriteLine("No match");
}
Run Code Online (Sandbox Code Playgroud)
将在字符串的开头捕获1-2位数字.
您可以使用LINQ:
string s = "35|...";
int result = int.Parse(new string(s.TakeWhile(char.IsDigit).ToArray()));
Run Code Online (Sandbox Code Playgroud)
或者(如果数字总是跟着a |)好的字符串操作:
string s = "35|...";
int result = int.Parse(s.Substring(0, s.IndexOf('|')));
Run Code Online (Sandbox Code Playgroud)