Delete row after row definition

I need to delete certain lines after another line inside a piece of text. I have a text file with some urls, and after the url there is a RESULT of operation. I need to delete the RESULT and leave only the URL.

Sample text:

http://website1.com/something Result: OK (registering only mode is on) 

http://website2.com/something Result: Problems registered 100% (SOMETHING ELSE) Other Strings; 

http: // web site 

I need to delete all lines starting with Result: so that the remaining lines are:

http://website1.com/something

http://website2.com/something

http://website3.com/something

Without Result: ........

The results are randomly generated, so I don’t know exactly what is after RESULT:

+5
source share
8 answers

One option is to use regular expressions according to some other answers. The other is only IndexOffollowed by Substring:

int resultIndex = text.IndexOf("Result:");
if (resultIndex != -1)
{
    text = text.Substring(0, resultIndex);
}

Personally, as a rule, I find that if I manage to deal with a few very simple and understandable string operations, it becomes easier for me to deal with the use of regular expressions. Once you start moving on to real patterns (at least three of them, then one of them), then regular expressions will become much more useful, of course.

+12
source

- string.Replace

var pattern = "Result:";
var lineContainYourValue = "jdfhkjsdfhsdf Result:ljksdfljh"; //I want replace test
lineContainYourValue.Replace(pattern,"");
+1
string input = "Action2 Result: Problems registered 100% (SOMETHING ELSE) Other Strings; ";
string pattern = "^(Action[0-9]*) (.*)$";
string replacement = "$1";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);

$1 ActionXX.

+1

Regex.

:

var r = new System.Text.RegularExpressions.Regex("Result:(.)*");
var result = r.Replace("Action Result:1231231", "");

"" .

+1

Linq:

IEnumerable<String> result = System.IO.File
    .ReadLines(path)
    .Where(l => l.StartsWith("Action") && l.Contains("Result"))
    .Select(l => l.Substring(0, l.IndexOf("Result")));
0

- ?

string line;
using ( var reader = new StreamReader ( File.Open ( @"C:\temp\test.txt", FileMode.Open ) ) )
   using ( var sw = new StreamWriter(File.Open( @"C:\Temp\test.edited.txt", FileMode.CreateNew ) ))
       while ( (line = reader.ReadLine()) != null )
          if(!line.StartsWith("Result:")) sw.WriteLine(line); 
0

RegEx .

using System.Text.RegularExpressions;

private string ParseString(string originalString)
{
    string pattern = ".*(?=Result:.*)";
    Match match = Regex.Match(originalString, pattern);
    return match.Value;
}
0

, -, .

var fileLine = "http://example.com/sub/     random text";
Regex regexPattern = new Regex("(.*?)\\s");
var websiteMatch = regexPattern.Match(fileLine).Groups[1].ToString();
Debug.Print("!" + websiteMatch + "!");

. Regex :. * ,? () , \\s .

0

All Articles