简体   繁体   English

使用C#在文本文件中搜索模式

[英]Search for a pattern in text file using c#

I have multiple text files.I need value 'UA-8798837-1' (without the qoutes) from the code below. 我有多个文本文件,我需要以下代码中的值'UA-8798837-1' (无qoutes)。 So steps will be-: 因此,步骤将是:

  1. open the text file abc.txt . 打开文本文件abc.txt。
  2. search for a pattern starting from "_gaq.push". "_gaq.push".开始搜索模式"_gaq.push".
  3. If pattern matches I will skip a few characters "(['_setAccount', ". 如果模式匹配,我将跳过几个字符"(['_setAccount', ".
  4. select the key 'UA-8798837-1' (without quotes). 选择键'UA-8798837-1' (不带引号)。
  5. Save this key value in a variable called "key". 将此键值保存在一个名为“ key”的变量中。

Text file's code -: 文本文件的代码-:

<script type="text/javascript">//<![CDATA[
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-8798837-1']);
<script>

So basically I need to search for a pattern and if that is found I need to skip a few characters to select a code which is after the character " ' " and copy this value till the character " ' " is found again. 因此,基本上我需要搜索一个模式,如果找到了一个模式,则需要跳过几个字符以选择一个在字符“”之后的代码,然后复制该值直到再次找到字符“”。 Selection start at character " ' " 'UA-8798837-1' and ends at character " ' " value is UA-8798837-1. 选择开始于字符" ' " 'UA-8798837-1' ,结束于字符" ' "值为UA-8798837-1。 Please tell me how to do it .Thanks in advance. 请告诉我该怎么做。谢谢。

This is a pretty simple regex: 这是一个非常简单的正则表达式:

/\\[\\'_setAccount\\', \\'(.+)\\'/

You can see what the matched groups will look like here. 您可以在此处看到匹配的组

And in case you haven't worked with regex in C# before, this is a good place to get started. 而且,如果您以前从未在C#中使用过正则表达式,那么是一个入门的好地方。 Since you want to work with multiple matches, this link is probably even more relevant. 由于您要处理多个匹配项, 因此此链接可能更相关。

I think you are looking for this regex: 我认为您正在寻找此正则表达式:

(?<=_gaq\.push\(\['_setAccount',\s')(.*)(?=')

If that will always be the case, you can use that regex to match the key that you are looking for . 如果情况总是如此,则可以使用该正则表达式来匹配您要查找的密钥。

But I will not give you the code for getting it in C# code, Please let me know what you tried. 但是我不会为您提供使用C#代码获取代码的代码,请让我知道您尝试了什么。 Thanks. 谢谢。

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM