Removing characters from a string passed from an HTML page [duplicate] - c#

This question already has answers here:
How to remove new line characters from a string?
(11 answers)
Closed 9 years ago.
I'm trying to trim a string of some character so I can put it in an SQL query. An example of what is being passed to my method is "\n asdw_value\n". I want the "\n"s and the space to be removed, but I can't get the "\n" to go away. My code now looks like this :
element = element.Replace("\\", "");
element = element.Replace("n", "");
element = element.Replace(" ", "");
And the output has been "\nasdq_value\n" Any help is appreciated.

Most likely the string value you're seeing is produced in the debugger. The \n is an escape sequence meaning 'newline'. It's a single character, not a \ followed by a n, so to remove it from your input, you will need to use the same escape sequence, like this:
element = element.Replace("\n", "");
element = element.Replace(" ", "");
If you only want to trim these characters from the beginning and end of the string, you can do this:
element = element.Trim(new char[] { '\n', ' ' });

Related

Removing all occurences of '\' from json response string not working [duplicate]

This question already has answers here:
How can I deserialize JSON with C#?
(19 answers)
C# string replace does not actually replace the value in the string [duplicate]
(3 answers)
Closed 3 years ago.
List item
I have a string object such as the following.
string mycontent = "\"The time is Valid\"\n"
string tocompare = "The time is Valid"
The contents of mycontent are assigned by the following line of code.
string mycontent = await response.Content.ReadAsStringAsync();
I want to be able to remove all the \n and the \ and to do that I do the following.
mycontent.Trim().Replace(#"\","")
I am trying to compare the mycontent and tocompare for equality. But this does not work.
if (string.Compare(tocompare, mycontent.Trim().Replace(#"\","")) == 0)
{
//TODO
}
For some reason which I do not know, I am not able to see equal to 0.
Am I missing something here? Any help is appreciated.
There are no actual slash characters in the string you showed. The slashes in the source code are part of the string literal syntax, where the \" represents just the character " (it needs to be escaped to distinguish it from the end of the string) and the \n represents a newline.
If you want to remove quotes and newlines from the sides of the string, you can do that with Trim too:
mycontent.Trim('"', '\n')
But that’s a bit of a weird thing to do. If this string actually represents some serialized format for the text you want, like JSON or CSV, you should use a parser for that instead. Where did you get it?
You have to replace slash first and then the quote
mycontent = mycontent.Trim().Replace(#"\", "").Replace(#"""", "")
In your case:
if (string.Compare(tocompare, mycontent.Trim().Replace(#"\","").Replace(#"""", "")) == 0)
{
//TODO
}
If you want to add a text slash to a string, you must type like this.
string mycontent = "\\"+"The time is Valid"+"\\"+"\n";
To delete slashes
mycontent=mycontent.Trim().Replace("\\","");

Trim is not returning a string without the characters I want to remove [duplicate]

This question already has answers here:
C# Trim() vs replace()
(8 answers)
Closed 3 years ago.
I want to remove 2 chars from a string: '-', '.'
According to microsoft documentation, if I provide a array of characters as a parameter to trim, it should remove then and return a new string.
Here is the code I trying:
char[] charsToTrim = { '-', '.'};
string newCPF = usuario.Cpf.Trim(charsToTrim);
usuario.Cpf = newCPF;
_context.Add(usuario);
The string is something like this 000.000.000-00, but trim is not removing the . and -
What I'm doing wrong?
Trim only removes the specified characters from the start and the end of the string.
You could just use String.Replace to remove those characters:
string newCPF = usuario.Cpf.Replace("-", "").Replace(".", "");

splitting the string and choosing the middle part containing two set of parenthesis [duplicate]

This question already has answers here:
How do I extract text that lies between parentheses (round brackets)?
(19 answers)
Closed 7 years ago.
As I know for selecting a part of a string we use split. For example, if node1.Text is test (delete) if we choose delete
string b1 = node1.Text.Split('(')[0];
then that means we have chosen test, But if I want to choose delete from node1.Text how can I do?
Update:
Another question is that when there are two sets of parenthesis in the string, how one could aim at delete?. For example is string is test(2) (delete) - if we choose delete
You can also use regex, and then just remove the parentheses:
resultString = Regex.Match(yourString, #"\((.*?)\)").Value.
Replace("(", "").Replace(")", "");
Or better:
Regex.Match(yourString, #"\((.*?)\)").Groups[1].Value;
If you want to extract multiple strings in parentheses:
List<string> matches = new List<string>();
var result = Regex.Matches(yourString, #"\((.*?)\)");
foreach(Match x in result)
matches.Add(x.Groups[1].Value.ToString());
If your string is always xxx(yyy)zzz format, you can add ) character so split it and get the second item like;
var s = "test (delete) if we choose delete";
string b1 = s.Split(new[] { '(', ')' })[1];
string tmp = node1.Text.Split('(')[1];
string final = tmp.Split(')')[0];
Is also possible.
With the index [x] you target the part of the string before and after the character you have split the original string at. If the character occurs multiple times, your resulting string hat more parts.

Remove characters between different parameters [duplicate]

This question already has an answer here:
Learning Regular Expressions [closed]
(1 answer)
Closed 7 years ago.
I have a string of different emails
ex: "email1#uy.com, email2#iu.it, email3#uu.edu" etc, etc
I would like to formulate a Regex that creates the following output
ex: "email1,email2,email3" etc, etc
How can I remove characters between an "#" and "," but leaving a "," and a Space in C#
Thank you so much for the help!!
If you want to replace all characters between # and comma by blank, the easiest option is to use Regex.Replace:
var emails = "a#m.com, b#m.com, d#m.com";
var result = Regex.Replace(emails, "#[^,]+", string.Empty);
// result is "a, b, d"
Please note that it leaves spaces after comma in the result, as you wanted in your question, though your example result has spaces removed.
The regular expression looks for all substrings starting '#' characters, followed by any character which is not comma. Those substrings are replaced with empty string.
Replacing all occurrences of #[^,]+ with an empty string will do the job.
The expression matches sequences that start in #, inclusive, up to a comma or to the end, exclusive. Therefore, commas in the original string of e-mails would be kept.
Demo.
Maybe you don't need to use a regex, in that case you can do the following:
string input = "email1#uy.com, email2#iu.it, email3#uu.edu";
input = input.Replace(" ", "");
string[] ocurrences = input.Split(',');
for (int i = 0; i < ocurrences.Length; i++)
{
string s = ocurrences[i];
ocurrences[i] = s.Substring(0, s.IndexOf('#'));
}
string final = string.Join(", ", occurences);

How to remove spaces and newlines in a string [duplicate]

This question already has answers here:
Fastest way to remove white spaces in string
(13 answers)
Closed 9 years ago.
sorry if they are not very practical for C # Asp.Net, I hope to make me understand
I have this situation
string content = ClearHTMLTags(HttpUtility.HtmlDecode(e.Body));
content=content.Replace("\r\n", "");
content=content.Trim();
((Post)sender).Description = content + "...";
I would make sure that the string does not contain content nor spaces (Trim) and neither carriage return with line feed, I'm using the above code inserted but it does not work great either
any suggestions??
Thank you very much
Fabry
You can remove all whitespaces with this regex
content = Regex.Replace(content, #"\s+", string.Empty);
what are whitespace characters from MSDN.
Btw you are mistaking Trim with removing spaces, in fact it's only removing spaces at the begining and at the end of string. If you want to replace all spaces and carige returns use my regex.
this should do it
String text = #"hdjhsjhsdcj/sjksdc\t\r\n asdf";
string[] charactersToReplace = new string[] { #"\t", #"\n", #"\r", " " };
foreach (string s in charactersToReplace)
{
text = text.Replace(s, "");
}
simple change only you missed # symbol
string content = ClearHTMLTags(HttpUtility.HtmlDecode(e.Body));
content=content.Replace(#"\r\n", "");
content=content.Trim();
((Post)sender).Description = content + "...";

Categories

Resources