以下代码存储在名为str1
的字符串中,number表示行号,text表示php代码行。现在,我想分别提取行号和代码行。
* 47: echo
<http://php.net/echo> echo "<div id=" . $var . ">content</div>";
o 46: $var = htmlspecialchars($v, ENT_QUOTES);
+ 45: $v = $_SESSION['UserData'];
直到现在,我已经尝试了
str1.Split(new char[] { ':', ';' });
但是这也会破坏'http:'中的字符串,并且在返回的数组中也包含wild char \ n \ r \ n。如何删除野生字符\ n \ r + o?或是否有其他方法可以在两个数字之间提取数字和字符串?
答案 0 :(得分:1)
试试这个:
string str1 = "47: echo <http://php.net/echo> echo \"<div id=\" . $var . \">content</div>\"; " + Environment.NewLine
+ "o 46: $var = htmlspecialchars($v, ENT_QUOTES);" + Environment.NewLine
+ "+ 45: $v = $_SESSION['UserData']; ";
var matches = System.Text.RegularExpressions.Regex.Matches(str1, @"([\d]+)?:(.*)?\r\n?", System.Text.RegularExpressions.RegexOptions.Multiline);
foreach(Match m in matches)
{
Console.WriteLine(m.Groups[1].Value);
Console.WriteLine(m.Groups[2].Value);
}
答案 1 :(得分:0)
Regex regex = new Regex(@"(?<LineNumber>\d+)[:](?<Code>.+)$");
using (StreamReader reader = new StreamReader("TextFile1.txt"))
{
string s = null;
while ((s = reader.ReadLine()) != null)
{
Match match = regex.Match(s);
if (match.Success)
{
Console.WriteLine("{0}: {1}", match.Groups["LineNumber"].Value,
match.Groups["Code"].Value);
}
}
}
输出:
47:回声
46:$ var = htmlspecialchars($ v,ENT_QUOTES);
45:$ v = $ _SESSION [&#39; UserData&#39;];