Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove text from string until it reaches a certain character

Tags:

string

c#

split

I'm having a issue trying to figure out this. I need to "fix" some links, here is an example:

  1. www.site.com/link/index.php?REMOVETHISHERE
  2. www.site.com/index.php?REMOVETHISHERE

So basically I want to remove everything till it reaches the ? character. Thanks for your help.

like image 532
Josh Mikel Avatar asked Dec 03 '11 23:12

Josh Mikel


People also ask

How do I remove all characters from a string before a specific character?

Remove everything before a character in a string using Regex We need to use the “. *-” as a regex pattern and an empty string as the replacement string. It deleted everything before the character '-' from the string.

How do I remove all characters from a string after a specific character?

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 trim a string before a specific character in Python?

lstrip() #strips everything before and including the character or set of characters you say. If left blank, deletes whitespace.. rstrip() #strips everything out from the end up to and including the character or set of characters you give. If left blank, deletes whitespace at the end.

How do you cut a string before a specific character in Java?

trim() . trim() removes spaces before the first character (which isn't a whitespace, such as letters, numbers etc.) of a string (leading spaces) and also removes spaces after the last character (trailing spaces).


2 Answers

 string s = @"www.site.com/link/index.php?REMOVETHISHERE";
 s = s.Remove( s.LastIndexOf('?') );
 //Now s will be simply "www.site.com/link/index.php"

should do it

like image 111
parapura rajkumar Avatar answered Oct 07 '22 22:10

parapura rajkumar


Although a properly crafted string operation will work, the more general way to extract partial URI information is to use the System.Uri type which has methods which encapsulate these operations, e.g.

var uri = new Uri("http://www.site.com/link/index.php?REMOVETHISHERE");
var part = uri.GetLeftPart(UriPartial.Path);

This will convey the intent of your code more clearly and you'll be re-using a current implementation which is known to work.

The System.Uri constructor will throw an exception if the string does not represent a valid URI, but you will anyway probably want to invoke some other behavior in your program if an invalid URI has been encountered. To detect an invalid URI you can either catch the exception or use one of the TryCreate() overloads.

like image 20
Adam Ralph Avatar answered Oct 07 '22 22:10

Adam Ralph