How to remove special characters with regex instead of Replace string - c#

My current method:
var q = new StringBuilder(query);
return q.Replace("'", " ")
.Replace("\"", " ")
.Replace(":", "")
.Replace("#", " ")
.Replace("/", " ")
.Replace("\\", " ")
.Replace(",", " ")
.Replace("&", " ")
.Replace("?", " ")
.Replace("%", " ")
.Replace(".", " ")
.Replace("quot;", " ")
.Replace("-", " ")
.Replace("*", " ")
.ToString().Trim();
How can I done this using regex for better performance?
Edited: Sorry, I want replace all special characters by space " ".

You could use this:
string q = Regex.Replace(query, #"[:#/\\]", ".");
q = Regex.Replace(q, #""|['"",&?%\.*-]", " ");
EDIT:
On closer inspection of what you're doing, your code is translating several characters into ., and then translating all . into spaces. So you could just do this:
string q = Regex.Replace(query, #""|['"",&?%\.*:#/\\-]", " ").Trim();
I'm not really sure what you're trying to do here, though. I feel like what you're really looking for is something like:
string q = Regex.Replace(query, #"[^\w\s]", "");
The presence of " in there throws me for a loop, and is why I'm not sure what you're doing. If you want to get rid of HTML entities, you could run query through HttpUtility.HtmlDecode(string) first and then apply the regex.

Try this.
string pattern = #"[^a-zA-Z0-9]";
string test = Regex.Replace("abc*&34567*opdldld(aododod';", pattern, " ");

Related

How to set prefix in string in join?

I have this strings:
string[] codes = new string[]{"66000110", "66000001", "66000121"};
I want to make join on strings above:
string filter = string.Join(" OR " + some_ID + "=", codes );
The resukt I get is:
some_ID=66000110 OR some_ID=66000001 OR some_ID=66000121
While I need the string like that(OR missing on start string):
OR some_ID=66000110 OR some_ID=66000001 OR some_ID=66000121
How do I fix elegantic way to get OR on start of the string?
It seems that you are building some kind of SQL; if it's your case, try switching to IN:
string filter = $" OR {some_ID} IN ({string.Join(", ", codes)})";
And you'll get a more readable equivalent
" OR some_ID IN (66000110, 66000001, 66000121)"
You can use a combination of LINQ and Concat():
string filter = string.Concat(codes.Select(c => " OR " + some_ID + "=" + c));
Why not something like this?
string filter = " or " + string.Join(" OR " + some_ID + "=", codes );

How to find and Replace a token in a c# string that starts with a value

I've got an issue where I am applying a template to an object and am using a find and replace function to mesh the template in the form of a string of html. The issue is, the height and width of the image are contained in the token so I don't have a way to find and replace as it could vary.
Token value is [ARTICLEIMAGE:150:200]
foreach(var article in articles) {
var articleTemplateValue = _TemplateArticleMarkup;
articleTemplateValue = articleTemplateValue.Replace("[ARTICLEIMAGE:xx:yy]", "<img src=" + article.ArticleImageFolder + "/" + article.ArticleImage + " title=" + article.ArticleTitle + " width="
xx" height="
yy" />");
}
This obviously would not work for every example as the dimensions of the image token will vary. Is there a way to find the token as a StartsWith and then split the dimensions an array on the :. Please let me know if that makes sense as it is a little confusing. Thanks!
Regex will solve this issue for you.
using System.Text.RegularExpressions;
Then change your code as seen below.
foreach (var article in articles)
{
string articleTemplateValue = _TemplateArticleMarkup;
MatchCollection mc = Regex.Matches(articleTemplateValue, #"\[ARTICLEIMAGE\:(\d+)\:(\d+)\]");
if (mc.Count > 0)
{
string toReplace = mc[0].Value;
string xx = mc[0].Groups[1].Value;
string yy = mc[0].Groups[2].Value;
articleTemplateValue = articleTemplateValue.Replace(toReplace, "<img src=\"" + article.ArticleImageFolder + "/" + article.ArticleImage + "\" title=\"" + article.ArticleTitle + "\" width=\"" + xx + "\" height=\"" + yy + "\"/>");
}
}
You can use the Split() command to find the width and the height. A very rough approach follows:
rextester remo
String articleTemplateValue = "[test:40:200]";
Console.WriteLine(articleTemplateValue);
var arr = articleTemplateValue.Split(':');
if (arr.Length == 3) {
var xx = arr[1];
var yy = arr[2].Substring(0, arr[2].Length - 1);
articleTemplateValue = articleTemplateValue.Replace(articleTemplateValue, "<img src="
+ "folder" + "/" + "image" + " title=" + "ArticleTitle" + " width="+ xx + " height= " + yy+ "/>");
Console.WriteLine(articleTemplateValue);
}
Use Regex would do the trick repl.it demo
"\[ARTICLEIMAGE:\d+?:\d+?\]"
\[ escape the [ character. Brackets are special characters in Regex
\d any digit
\d+?: + is 0 or more digits. Until we find a colon :. The ? means non-greedy and is really not needed...
\] escape the closing bracket
var matches = Regex.Match(articleTemplateValue, #"\d+");
var xx = matches;
var yy = matches.NextMatch();
var template = "<img src=" + article.ArticleImageFolder + "/" + article.ArticleImage + " title=" + article.ArticleTitle + " width="
+ xx + " height="
+ yy + " />";
articleTemplateValue = articleTemplateValue = Regex.Replace(articleTemplateValue, #"\[ARTICLEIMAGE:\d+?:\d+?\]", template);
Using
Regex.Match(string, string)
Regex.Replace(string, string)

C# String/StringBuilder MemoryException on Large set of Replaces

I am trying to figure out a better way to manipulate a large string and using both string and string builder I am unable to.
What I have below is a function that takes in a string and we search that string with regex to find any links. Any occurances of links I want to wrap them in a valid link text. My issue is , I have a database entry (string) with 101 link values present that need to be replaced and I am getting memory issues.
Is there a better way around this solution. I have included it with both string.replace and stringbuilder.replace and neither work
var resultString = new StringBuilder(testb);
Regex regx = new Regex(#"((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+#)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+#)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%#.\w_]*)#?(?:[.\!\/\\w]*))?)", RegexOptions.IgnoreCase);
MatchCollection mactches = regx.Matches(txt);
foreach (Match match in mactches)
{
if(match.Value.StartsWith("http://") || match.Value.StartsWith("https://"))
fixedurl = match.Value;
else
fixedurl = "http://" + match.Value;
resultString.Replace(match.Value, "<a target='_blank' class='ts-link ui-state-default' href='" + fixedurl + "'>" + match.Value + "</a>");
//testb = testb.Replace(match.Value, "<a target='_blank' class='ts-link ui-state-default' href='" + fixedurl + "'>" + match.Value + "</a>");
}
You can try the following. It may perform better in your specific case.
Regex regx = new Regex(#"((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+#)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+#)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%#.\w_]*)#?(?:[.\!\/\\w]*))?)", RegexOptions.IgnoreCase);
string resultString = regx.Replace(txt, (match) =>
{
string fixedurl = (match.Value.StartsWith("http://") || match.Value.StartsWith("https://"))
? match.Value
: "http://" + match.Value;
return "<a target='_blank' class='ts-link ui-state-default' href='" + fixedurl + "'>" + match.Value + "</a>";
});
EDITED:
BTW, the issue with your code seems to be the resultString.Replace call, since it replaces all the occurrences of the string it's probably causing the code to enter into an infinite loop of replacing the same strings over and over again until it hits an OutOfMemoryException.

What is the replacement Sql Char(13) and isnull in Entity Framework?

I am new to Entity framework, Can any body tell me how to write the following query into Entity framework.
select column1 + char(13) +isnull(column2,space(1))+char(13)+isnull(column3,space(1))+char(13)+isnull(column4,space(1)) +char(13)+isnull(olumn5,space(1)) as FADRS
FROM table
Convert the above query into Entity Framework.
By using Jon answer i get the answer. Know my problem is how to use iqueryable
IQuer<string> Madr = from b in context.table
where b.column1 == txtaddrss.Text
select new
{FADR = b.column2 + '\r' +
(b.column3 ?? " ") + '\r' +
(b.column4 ?? " ") + '\r' +
(b.column5 ?? " ") + '\r' +
(b.column6 ?? " ")};
foreach(string something in Madr)
{
MessageBox.Show(something);
}
i am getting error conversion failed because of anonymous type
char(13) just does the equivalent (though more limited) of (char)13 in C#, which would just return '\r'.
Hence you would either use '\r' or "\r".
isnull(x, y)just does the equivalent of x ?? y in C#.
So you would use something like:
var query = from item in TableSource select
item.column1 + '\r' +
(item.column2 ?? " ") + '\r' +
(item.column3 ?? " ") + '\r' +
(item.column4 ?? " ") + '\r' +
(item.column5 ?? " ");
TableSource is whatever way you are getting a reference to the table (context.Table or whatever).
query will be an IQueryable<string> returning the relevant strings when invoked. If you really want the FADRS name from your example then the following will instead of strings return anonymous objects with a FADRS property:
var query = from item in TableSource select
new {FADRS = item.column1 + '\r' +
(item.column2 ?? " ") + '\r' +
(item.column3 ?? " ") + '\r' +
(item.column4 ?? " ") + '\r' +
(item.column5 ?? " ")};
Edit:
The first example above can be used as:
foreach(string something in query)
MessageBox.Show(something);
The second example as:
foreach(var something in query)
MessageBox.Show(something.FADR);
With the first var is optional shorthand, with the second you must use var as the types involved are anonymous, and hence var is the only way to name the type (by not naming it at all).
Given no further context I'd say sonething like this:
var query = from obj in context.table
select new {
FADR = obj.column1 + "\r" +
obj.column2 ?? " " + "\r" +
obj.column3 ?? " " + "\r" +
obj.column4 ?? " " + "\r" +
obj.column5 ?? " " + "\r" };

c# replace timestamp value string of text in textfield

i currently have a textbox field, everytime a change is made, i add who it was updated by and what time
right now it keep appending that text
how can i find the line that says "LastEdited: ", and only replace the time stamp value?
this is what i do now
maybe someone can post me example of code how to grab the timestamp and replace it?
if (txtMemberNotesOriginally != txtMemberNotesChanged) {
txtMemberNotes.AppendText("LastEdited: " + DateTime.Now.ToString() + " By: " + MyProgramName.Username + Environment.NewLine);
i am not an expert, so an example of code would bevery useful
i do use this textbox to save other notes as well (which i wouldn't wanna loose)
can i do this
foreach (var line in txtMemberNotes.Lines) {
if (line.StartsWith("Last Edited: "))
{
txtMemberNotes.Text = txtMemberNotes.Text.Replace(line, "Last Edited: " + DateTime.Now.ToString() + " By: " + MyProgramName.Username + Environment.NewLine);
}
else
{
txtMemberNotes.AppendText("Last Edited: " + DateTime.Now.ToString() + " By: " + MyProgramName.Username + Environment.NewLine);
}
}
The easiest way to solve your problem seems to stop appending text and just set the text value. No parsing is necessary, just overwrite the exiting values with your newer value.
if (txtMemberNotesOriginally != txtMemberNotesChanged) {
txtMemberNotes.Text = "LastEdited: " + DateTime.Now.ToString() + " By: " + MyProgramName.Username + Environment.NewLine;
I guess theres always Regex if you really wanted:
string s = #"Some notes here etc etc..
Last edited: 12/12/2012 12:00:00 AM";
Console.Write(Regex.Replace(s, #"Last edited: .*$", "Lasted edited: " + DateTime.Now.ToString()));
Or more specifically using your code:
txtMemberNotes.Text = Regex.Replace(txtMemberNotes.Text, #"Last edited: .*$", "Lasted edited: " + DateTime.Now.ToString());

Categories

Resources