之前和之后搜索字符串和读取字符 [英] Search string and read chracters after and before

查看:90
本文介绍了之前和之后搜索字符串和读取字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码在文件中查找指定的字符串(server =)



The following code finds the specified strings (server=") in a file

atic void Main(string[] args)
        {

            string fName = @"C:\Temp\MyFile";

            StreamReader testTxt = new StreamReader(fName);

            string allRead = testTxt.ReadToEnd();

            testTxt.Close(); 

            string regMatch = "server=";
           
           

            if (Regex.IsMatch(allRead,regMatch))

            {

                Console.WriteLine("found\n");
            


        }

            else

         {

                Console.WriteLine("not found\n");

            }

       The actual string in the file looks like server="HostName"
Since I found the server=" 
how do I read the next characters until I run into (")?
many thanks


        }





我尝试过:



我一直在googl但没有运气



What I have tried:

I have been googl this but no luck

推荐答案

如果您使用Match对象:

If you use the Match object:
string regMatch = "server=";
Match m = Regex.Match(allRead, regMatch);
if (m.Success)
    {

然后您可以使用其属性告诉您它的位置:

Then you can use its properties to tell you where it was found:

string regMatch = "server=";
Match m = Regex.Match(allRead, regMatch);
if (m.Success)
    {
    int startOfMatch = m.Index;
    int lengthOfMatch = m.Length;
    char justBefore = allRead[startOfMatch - 1];
    char justAfter = allRead[startOfMatch + lengthOfMatch];
    }


这篇关于之前和之后搜索字符串和读取字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆