我收到这样的字符串:
"????log L 05/27/2012 - 08:02:57: \"Acid<1><STEAM_ID_PENDING><CT>\" say \"password somepass\"\n\0"
我怎样才能somepass
从这个字符串中得到?
您想要的比赛在第 1 组
\"password (.*?)\\"\\n\\0"
在 C# 中,这变成
string resultString = null;
Regex regexObj = new Regex(@"""password (.*?)\\""\\n\\0""");
resultString = regexObj.Match(subjectString).Groups[1].Value;
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