我收到了一个像这样的字符串:
"????log L 05/27/2012 - 08:02:57: \"Acid<1><STEAM_ID_PENDING><CT>\" say \"password somepass\"\n\0"
如何从此字符串中获取somepass
?
答案 0 :(得分:3)
您想要的比赛是
的第1组\"password (.*?)\\"\\n\\0"
在C#中,这变为
string resultString = null;
Regex regexObj = new Regex(@"""password (.*?)\\""\\n\\0""");
resultString = regexObj.Match(subjectString).Groups[1].Value;
答案 1 :(得分:2)
string test = "????log L 05/27/2012 - 08:02:57: \"Acid<1><STEAM_ID_PENDING><CT>\" say \"password somepass\"\n\0";
string[] array = test.Split('\"'); ;
Console.WriteLine(array[3].Split(' ').Last()); //somepass
或者:
string password = string.Empty;
for (int i = 0; i < test.Length - 8; i++)
if (test.Substring(i, 8) == "password")
for (int j = i + 8; test[j] != '\"'; j++)
if (test[j] != ' ')
password += test[j];
Console.WriteLine(password); //somepass
我对buckley
给出的答案感兴趣,所以我使用这三种方法做了一个基准来获得"somepass"
,使用这段代码:
string test = "????log L 05/27/2012 - 08:02:57: \"Acid<1><STEAM_ID_PENDING><CT>\" say \"password somepass\"\n\0";
Stopwatch timer = new Stopwatch();
timer.Start();
for (int n = 0; n < 10000000; n++)
{
string[] array = test.Split('\"');
string password = array[3].Split(' ').Last(); //somepass
}
timer.Stop();
TimeSpan time = timer.Elapsed;
Console.WriteLine(String.Format("{0:00}:{1:00}:{2:00}", time.Minutes, time.Seconds, time.Milliseconds / 10));
timer.Reset();
timer.Start();
for (int n = 0; n < 10000000; n++)
{
string password = string.Empty;
for (int i = 0; i < test.Length - 8; i++)
if (test.Substring(i, 8) == "password")
for (int j = i + 8; test[j] != '\"'; j++)
if (test[j] != ' ')
password += test[j];
} //somepass
timer.Stop();
time = timer.Elapsed;
Console.WriteLine(String.Format("{0:00}:{1:00}:{2:00}", time.Minutes, time.Seconds, time.Milliseconds / 10));
timer.Reset();
timer.Start();
for (int n = 0; n < 10000000; n++)
{
string resultString = null;
Regex regexObj = new Regex(@"""password (.*?)\\""\\n\\0""");
resultString = regexObj.Match(test).Groups[1].Value; //somepass
}
timer.Stop();
time = timer.Elapsed;
Console.WriteLine(String.Format("{0:00}:{1:00}:{2:00}", time.Minutes, time.Seconds, time.Milliseconds / 10));
结果是(快照):
我可以得出结论,在这种情况下,使用Split()
方法( 1475%)比使用Regex
方法更快。