Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove String After Determinate String

Tags:

c#

.net

I need to remove certain strings after another string within a piece of text. I have a text file with some URLs and after the URL there is the RESULT of an operation. I need to remove the RESULT of the operation and leave only the URL.

Example of 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://website3.com/something                               Result: error: "Âíèìàíèå, îáíàðóæåíà îøèáêà - Ìåñòî æèòåëüñòâà ñîäåðæèò íåäîïóñòèìûå ê 

I need to remove all strings starting from Result: so the remaining strings have to be:

http://website1.com/something

http://website2.com/something

http://website3.com/something

Without Result: ........

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

like image 832
GCiri Avatar asked Sep 03 '12 12:09

GCiri


People also ask

How do you delete everything after a certain character in a string?

To remove everything after a specific character in a string:Use the String. split() method to split the string on the character. Access the array at index 0 . The first element in the array will be the part of the string before the specified character.

How do you remove a string after a specific character in Java?

The idea is to use the deleteCharAt() method of StringBuilder class to remove first and the last character of a string. The deleteCharAt() method accepts a parameter as an index of the character you want to remove.


2 Answers

One option is to use regular expressions as per some other answers. Another is just IndexOf followed by Substring:

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

Personally I tend to find that if I can get away with just a couple of very simple and easy to understand string operations, I find that easier to get right than using regex. Once you start going into real patterns (at least 3 of these, then one of those) then regexes become a lot more useful, of course.

like image 134
Jon Skeet Avatar answered Oct 06 '22 01:10

Jon Skeet


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);

You use $1 to keep the match ActionXX.

like image 40
LaGrandMere Avatar answered Oct 06 '22 00:10

LaGrandMere