I'm having a issue trying to figure out this. I need to "fix" some links, here is an example:
So basically I want to remove everything till it reaches the ? character. Thanks for your help.
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.
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.
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.
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).
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With