Как найти конкретное значение в строке

1

У меня есть это:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
   public class Program
    {
        static void Main(string[] args)
        {

            //Consider making this configurable
            const string sourceFile = "testSolar.txt";
            const string pattern = "http://10.123.9.66:80";
            const string lastName = "nosyn_name_last_exact:";
            Regex re = new Regex("^(http|https)://");
            HttpWebResponse response;



            //var res = re.Match(str);


           // var webClient = new WebClient();
            var times = new Dictionary<string, TimeSpan>();
            var stopwatch = new System.Diagnostics.Stopwatch();

            //Add header so if headers are tracked, it will show it is your application rather than something ambiguous
            //webClient.Headers.Add(HttpRequestHeader.UserAgent, "Response-Tester-Client");

            var urlList = new List<string>();

            //Loop through the lines in the file to get the urls 
            try
            {
                stopwatch.Start();
                using (var reader = new StreamReader(sourceFile))
                {

                    while (!reader.EndOfStream)
                    {
                        var urNewList = new List<string>();
                        var line = reader.ReadLine();
                        //line = line.Substring(line.IndexOf(pattern));
                        //line.Split("\t");
                        var columns = line.Split('\t');

                        if (columns[2] == "R")
                        {
                            var url = columns[4] + "?" + columns[5];
                            urlList.Add(url);
                            Thread.Sleep(250);
                        }
                        if (columns[5] == lastName)
                        {
                            MatchCollection matches = Regex.Matches(line, lastName);
                        }

                    }
                }
            }

            catch (Exception e)
            {
                Console.WriteLine("An error occured while attempting to access the source file at {0}", sourceFile);
            }
            finally
            {
                //Stop, record and reset the stopwatch
                stopwatch.Stop();
                times.Add("FileReadTime", stopwatch.Elapsed);
                stopwatch.Reset();
            }

            //Try to connect to each url
            var counter = 1;
            foreach (var url in urlList)
            {
                try
                {
                    stopwatch.Start();

                    using (WebClient webClient = new WebClient())
                    {

                        webClient.Headers.Add(HttpRequestHeader.UserAgent, "Response-Tester-Client");

                       // HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                        request.Method = "POST";


                        //HttpWebResponse responses = (HttpWebResponse)request.GetResponse();

                        //Stream receiveStream = responses.GetResponseStream();

                        //StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);

                        //String a = readStream.ReadToEnd();


                        //webClient.DownloadString(url);




                        //webClient.Dispose();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error occured while attempting to connect to {0}", url);
                }
                finally
                {
                    stopwatch.Stop();

                    //We use the counter for a friendlier url as the current ones are unwieldly
                    times.Add("Url " + counter, stopwatch.Elapsed);
                    counter++;

                    stopwatch.Reset();
                }
            }

            //Release the resources for the WebClient 
            //webClient.Dispose();

            //Write the response times

            Console.WriteLine("Url " +  "\t\t\t\tLast Name ");
            foreach (var key in times.Keys)
            {
                Console.WriteLine("{0}: {1}", key, times[key].TotalSeconds);
            }


            Console.ReadKey();
        }
    }
}

и это моя строка:

2014-08-25 14:20:45,478 DEV z5gyjtcexs41vra4yegqejcf    0   R   .   http://10.123.9.66:80/solr_3.6/combi_live/select/   qt=standard_a2aperson&q=(((((nosyn_name_last_b_exact:(qxqkuilenburgqxq))))))&fq=(nosyn_name_last_exact:(qxqbroekqxq))&spellcheck.q=(qxqbroekqxq  kuilenburg)&fq=(fk_collectiontype:6)&spellcheck=true&spellcheck.count=-3&start=10&sort=date_main asc, score desc&omitHeader=true

теперь я хочу, чтобы он искал эту строку: nosyn_name_last_exact, а затем answare: qxqbroekqxq должен быть отфильтрован. Я уже поставил для него код som. Немного помочь закончить это будет хорошо

Спасибо

  • 0
    что вы подразумеваете под ".... должен быть отфильтрован"? Отфильтрованный как? Вы хотите извлечь это?
  • 0
    да, извлечено и записано на экран
Показать ещё 1 комментарий
Теги:
string

1 ответ

0
Лучший ответ

Я бы пошел с простым String.Split() с этим:

string source = "2014-08-25 14:20:45,478 DEV z5gyjtcexs41vra4yegqejcf    0   R   .   http://10.123.9.66:80/solr_3.6/combi_live/select/   qt=standard_a2aperson&q=(((((nosyn_name_last_b_exact:(qxqkuilenburgqxq))))))&fq=(nosyn_name_last_exact:(qxqbroekqxq))&spellcheck.q=(qxqbroekqxq  kuilenburg)&fq=(fk_collectiontype:6)&spellcheck=true&spellcheck.count=-3&start=10&sort=date_main asc, score desc&omitHeader=true";
string[] Seperator = new[] {"nosyn_name_last_exact:("};
var result = source.Split(Seperator, StringSplitOptions.RemoveEmptyEntries)[1].Split(')')[0].Dump();

Выход: Изображение 174551

//EDIT: Не имеет значения, находится ли он в файле. Если вы читаете строку, вы читаете строку, поэтому код остается в силе. Обновленный код с правильным расщеплением в соответствии с комментариями:

string[] FirstSeparator = new[] {"nosyn_name_last_exact:(qxq"};
string[] SecondSeparator = new[] {"qxq)"};

foreach (string line in File.ReadLines(sourceFile))
{
    var temp = source.Split(FirstSeparator, StringSplitOptions.RemoveEmptyEntries)[1];
    var result = temp.Split(SecondSeparator, StringSplitOptions.RemoveEmptyEntries)[0];
    //or any other output ... Results in "broek"
    result.Dump("Result: ");
}

Если вы хотите читать только одну строку или две строки, вы также можете использовать средство для очистки потока:

 using (System.IO.StreamReader reader = new System.IO.StreamReader("myFile.txt")) 
 {
     //read the line
     string line = reader.ReadLine();
     //... do stuff as above
 }
  • 0
    Спасибо, Серв. Для вас, но строки в текстовом файле. и на самом деле вы должны получить только имя: так в этом случае: broek - так без qxq в начале и qxq до конца строки: qxqbroekqxq
  • 0
    Да, Serv, большое спасибо, но как получить только Broek? Так что без qxq до и после: qxqbroekqxq
Показать ещё 3 комментария

Ещё вопросы

Сообщество Overcoder
Наверх
Меню