Nothing happens when using Regex in asp.net - c#

Regex really does nothing if i run this code:
input contains: "geeeeekdldn"
Regex.Replace(input, #"g(.|\n)*?n", string.Empty);
normally after regex the value of input is "" but i still get "geeeeekdldn"
can someone help me please

You need to assign the output of the Replace to a new string:
string output = Regex.Replace(input, #"g(.|\n)*?n", string.Empty);
Replace doesn't update the input string - see the MSDN documentation - because (as Hans points out) .NET strings are immutable and cannot, therefore, be changed. So any method that manipulates a string must return a new string rather than updating the supplied string.

Regex.Replace is a function which has the string with the replacement made as its return value. At the moment you are discarding this return value. You probably want
string processedInput = Regex.Replace(input, #"g(.|\n)*?n", string.Empty);

In addition to all the (correct) answers: the String type in .Net is immutable, meaning that a string value can only be replaced, not changed. So all functions that work on a string always return a new one instead of changing the argument.

Related

Replacing backslash in a string

I am having a few problems with trying to replace backslashes in a date string on C# .net.
So far I am using:
string.Replace(#"\","-")
but it hasnt done the replacement. Could anyone please help?
string.Replace does not modify the string itself but returns a new string, which most likely you are throwing away. Do this instead:
myString= myString.Replace(#"\","-");
On a side note, this kind of operation is usually seen in code that manually mucks around with formatted date strings. Most of the time there is a better way to do what you want (which is?) than things like this.
as all of them saying you need to take value back in the variable.
so it should be
val1= val1.Replace(#"\","-");
Or
val1= val1.Replace("\\","-");
but not only .. below one will not work
val1.Replace(#"\","-");
Use it this way.
oldstring = oldstring.Replace(#"\","-");
Look for String.Replace return type.
Its a function which returns a corrected string. If it would have simply changed old string then it would had a void return type.
You could also use:
myString = myString.Replace('\\', '-'));
but just letting you know, date slashes are usually forward ones /, and not backslashes \.
As suggested by others that String.Replace doesn't update the original string object but it returns a new string instead.
myString= myString.Replace(#"\","-");
It's worthwhile for you to understand that string is immutable in C# basically to make it thread-safe. More details about strings and why they are immutable please see links here and here

what is the best way to parse out string from longer string?

i have a string that looks like this:
"/dir/location/test-load-ABCD.p"
and i need to parse out "ABCD" (where ABCD will be a different value every day)
The only things that i know that will always be consistent (to use for the logic for parsing) are:
There will always be be a ".p" after the value
There will always be a "test-load-" before the value.
The things i thought of was somehow grab everything past the last "/" and then remove the last 2 characters (to take case of the ".p" and then to do a
.Replace("test-load-", "")
but it felt kind of hacky so i wanted to see if people had any suggestions on a more elegant solution.
You can use a regex:
static readonly Regex parser = new Regex(#"/test-load-(.+)\.p");
string part = parser.Match(str).Groups[1].Value;
For added resilience, replace .+ with a character class containing only the characters that can appear in that part.
Bonus:
You probably next want
DateTime date = DateTime.ParseExact(part, "yyyy-MM-dd", CultureInfo.InvariantCulture);
Since this is a file name, use the file name parsing facility offered by the framework:
var fileName = System.IO.Path.GetFileNameWithoutExtension("/dir/location/test-load-ABCD.p");
string result = fileName.Replace("test-load-", "");
A “less hacky” solution than using Replace would be the use of regular expressions to capture the solution but I think this would be overkill in this case.
string input = "/dir/location/test-load-ABCD.p";
Regex.Match(input, #"test-load-([a-zA-Z]+)\.p$").Groups[1].Value

C# Regular expression problem

I have the following string:
http://www.powerwXXe.com/text1 123-456 text2 text3/
Can someone give me advice on how to get the value of text1, text2 and text3 and put them into a string. I have heard of regular expressions but have no idea how to use them.
Instead of going the RegEx route, if you know that the string will always be of a similar format, you can using string.Split, first on /, then on space and retrieve the results from the resulting string arrays.
string[] slashes = myString.Split('/');
string[] textVals = slashes[3].Split(' ');
// at this point:
// textVals[0] = "text1"
// textVals[1] = "123-456"
// textVals[2] = "text2"
// textVals[3] = "text3"
Here is a link on getting started with regular expressions in C#:Regular Expression Tutorial
I don't think it is appropriate to write out a tutorial here since the information is online, so please check out the link and let me know if you have a specific question.
Instead of using regex, you can use string.Fromat("http://myurl.com/{0}{1}{2}", value1, textbox2.Text, textbox3.Text) and format the url in whatever fashion. If you are looking to go the regex route, you can always check regexlib.
The use of regular expressions relies on patterns you see in your strings - you need to be able to generalize the pattern of strings you're looking for before you can use a regular expression.
For a problem of this scope, if you can pin down the pattern, you're probably better off using other string parsing methods, such as String.IndexOf and String.Split.
Regular expressions is a powerful tool, and certainly worth learning, but it might not be necessary here.
Based on the example you gave, it looks as though text1, text2 and text3 are separated by spaces? If so, and if you always know the positions they'll be in, you may want to skip regular expressions and just use .Split(' ') to split the string into an array of strings and then grab the pertinent items from there. Something like this:
string foo = "http://www.powerwXXe.com/text1 123-456 text2 text3/"
string[] fooParts = foo.Split(' ');
string text1 = fooParts[0].Replace("http://www.powerwXXe.com/", "");
string text2 = fooParts[2];
string text3 = fooParts[3].Replace("/", "");
You'd want to perform bounds checking on the string[] before trying to grab anything from it, but this would work. Regex is awesome for string parsing, but when it's simple stuff you need to do, sometimes it's overkill when simple methods from the string class will do.
It all depends on how much you know about about the string you are parsing. Where does the string come from and how much do you know about it's formating?
Based on your example string you could get away with something as simple as
string pattern = #"http://www.powerwXXe.com/(?<myGroup1>\S+)\s\S+\s(?<myGroup2>\S+)\s(?<myGroup3>\S+)/";
var reg = new System.Text.RegularExpressions.Regex(pattern);
string input = "http://www.powerwXXe.com/text1 123-456 text2 text3/";
System.Text.RegularExpressions.Match myMatch = reg.Match(input);
The caputerd strings would then be contained in myMatch.Groups["myGroup1"], ["myGroup2"], ["myGroup3"] respectivly.
This however assumes that your string always begins with http://www.powerwXXe.com/, that there will always be three groups to capture and that the groups are separated by a space (which is an illegal character in url's and would in almost all cases be converted to %20, which would have to be accounted for in the pattern).
So, how much do you know about your string? And, as some has already stated, do you really need regular expressions?

asp.net regex.replace()

I have the following code to first remove html tags and then highlight the search term within the resulting text:
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
try
{
// get search value query string
string searchText = Request.QueryString["search"].Trim();
string encodedValue = Server.HtmlEncode(searchText);
Literal Content = e.Item.FindControl("Content") as Literal;
string contentText = Content.Text;
Content.Text = Regex.Replace(contentText, #"<(.|\n)*?>", string.Empty).Replace(encodedValue, "<font class='highlight2'>" + encodedValue + "</font>");
}
catch
{
// do nothing
}
}
This works to a degree but the second replace is not case insensitive. How can I do the second replace also with regex.replace() so case sensitivity is not an issue? Thank you!
Use this overload which takes in RegexOptions. You'll want the IgnoreCase value.
First let's talk about the regex you're using to remove the tags, <(.|\n)*?>. If you want the dot to match anything including a newline, you should use Singleline mode. It's also known as DOTALL mode in some flavors, because that's what it does: allows the dot to match newlines. You can use the RegexOptions.Singleline flag for that, or embed it in the regex with an inline modifier:
`(?s)<.*?>`
This is still pretty fragile, but I'll leave it at that because there's no way to make it bulletproof; regexes and HTML are fundamentally incompatible.
As for the second replacement, the first thing you need to do is break up those chained method calls--in fact, I would say they never should have been chained. Feeding the result of a Regex.Replace directly to String.Replace is either an error or excessively clever. In either case, you have to split them up if you want to call Regex.Replace twice.
You also need to escape any regex metacharacters the search expression, assuming you still want to do a literal search and not a regex search. You can use the Escape method for that.
string searchText = Request.QueryString["search"].Trim();
string encodedValue = Server.HtmlEncode(searchText);
string escapedValue = Regex.Escape(encodedValue);
string contentText = Content.Text;
contentText = Regex.Replace(contentText, #"(?s)<.*?>", string.Empty);
contentText = Regex.Replace(contentText, escapedValue,
"<font class='highlight2'>$&</font>", RegexOptions.IgnoreCase);
Content.Text = contentText;
There are a few other things in your code that don't seem right to me (like why you seem to be permanently removing all the tags), but I'm trying to stay focused on your actual question. To that end, I've tried to make the minimum necessary changes in the code to illustrate my answer. But there's one more thing I just have to comment on:
catch
{
// do nothing
}
Don't do that. At the very least, send an error message to the console or rethrow the exception for the calling code to deal with, but never silently swallow them.

How can I replace "/" with "\/" in a string?

I would like to do the following:
if (string.Contains("/"))
{
string.Replace("/", "\/"); //this isn't valid
}
I've tried
string.Replace("/", "\\/");
but this gives me what I started with. How can I do this?
Thanks
Strings are immutable, which means that any modification you do to a string results in a new one, you should assign the result of the Replace method:
if (myString.Contains("/"))
{
myString = myString.Replace("/", "\\/");
}
String.Replace returns the string with replacements made - it doesn't change the string itself. It can't; strings are immutable. You need something like:
text = text.Replace("/", "\\/");
(In future examples, it would be helpful if you could use valid variable names btw. It means that those wishing to respond with working code can use the same names as you've used.)
One way is to use a verbatim string literal
string.Replace("/", #"\");

Categories