下面的代码存储在一个名为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:‘中中断字符串,并在返回的数组中包含野生char \n \r。我如何去除野生炭\n \n+ o?或者还有其他方法来提取两个数字之间的数字和字符串吗?
发布于 2014-12-22 19:26:01
试试这个:
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);
}发布于 2014-12-22 19:34:18
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: echo 46: $var = htmlspecialchars($v, ENT\_QUOTES); 45: $v = $\_SESSION['UserData'];https://stackoverflow.com/questions/27608981
复制相似问题