Assume I have a string "2.36" and I want it trimmed to "236"
I used Trim function in example
String amount = "2.36";
String trimmedAmount = amount.Trim('.');
The value of trimmedAmount is still 2.36
When amount.Trim('6'); it works perfectly but with '.'
What I am doing wrong?
Thanks a lot
Cheers
Trimming is removing characters from the start or end of a string.
You are simply trying to remove the ., which can be done by replacing that character with nothing:
string cleanAmount = amount.Replace(".", string.Empty);
If you want to remove everything but the digits:
String trimmedAmount = new String(amount.Where(Char.IsDigit).ToArray());
or:
String trimmedAmount = Regex.Replace(amount, #"\D+", String.Empty);
String.Trim removes leading and trailing whitespace. You need to use String.Replace()
Like:
string amount = "2.36";
string newAmount = amount.Replace(".", "");
Two ways :
string sRaw = "5.32";
string sClean = sRaw.Replace(".", "");
Trim is make for removing leading and trailings characters (such as space by default).
Related
How can I append a known string before each coma on a comma separated string.
Is there a regex for that or something that doesn't use a loop
EX
given string :
email, email2, email3 (etc...)
to
string suffix = "#iou.com"
string desiredResult = "email#iou.com, email2#iou.com, email3#iou.com
Thank you!!
You can use [^,\s]+ regexp, and replace with "$0"+suffix:
var res = Regex.Replace(original, #"[^,\s]+", "$0"+suffix);
"$0" refers to the content captured by the regular expression.
Demo.
Or using LINQ:
Console.WriteLine(string.Join(",",input.Split(',').Select(s => string.Concat(s, suffix))));
You could use a zero-length capture group. Here's how that might look:
\w+(?<ReplaceMe>),?
The \w matches alphanumeric characters, and the named capture group called "ReplaceMe" matches the zero-length space between the end of the word and the beginning of the comma (or any other non-alphanumeric item, including the end of the string).
Then you'd just replace ReplaceMe with the appended value, like this:
Regex.Replace(original, #"\w+(?<ReplaceMe>),?", "#email.com");
Here's an example ofthat regex in action.
Here you are:
string input = "email, email2, email3";
string suffix = "#iou.com";
//string desiredResult = "email#iou.com, email2#iou.com, email3#iou.com";
Console.WriteLine(Regex.Replace((input + ",")
.Replace(",", suffix + ","), #",$", ""));
Hope this helps.
Regex rgx2 = new Regex("[^[0-9] . \n\r\t]");
string dash = Regex.Replace(Des_AccNo.ToString(), #" ^-");
I need to clean this string 100-0#/2^2341?! as 100022341
I don't know what is your code, but you can do that by:
val = val.Replace("-", string.Empty)
If you want to remove all non-numeric characters:
string result = Regex.Replace(inputString, #"[^0-9]", "");
Basically what that says is "if the character isn't a digit, then replace it with the empty string." The ^ as the first character in the character group negates it. That is, [0-9] matches any digit. [^0-9] matches everything except a digit. See Character Classes in the MSDN documentation.
The expression #"[^\d]" also would work
I would basically create a static class that automatically pops up against any string.
If the same is GUID, you can simply do
Guid.NewGuid().ToString("N") returns only characters
Input: 12345678-1234-1234-1234-123456789abc
Output: 12345678123412341234123456789abc
public static string ToNonDashed(this string input)
{
return input?.Replace("-", string.Empty);
}
You can try this:
Des_AccNo = Des_AccNo.Replace("-", string.Empty);
string dash = Des_AccNo.ToString().Replace("-", string.Empty);
I want to remove all spaces(only ' ' and '\t', '\r\n' should stay) from string. But i have problem.
Example:
if i have
string test = "902322\t\r\n900657\t\r\n10421\t\r\n";
string res = test.Trim(); // res still "902322\t\r\n900657\t\r\n10421\t\r\n"
res = test.Trim('\t'); // res still "902322\t\r\n900657\t\r\n10421\t\r\n"
But if i have
string test = "902322\t";
Trim() work perfectly. Why this behavior? How i can remove '\t' from string using Trim() method?
String.Trim method deals only with whitespaces at the beginning and the end of the string
So you should use String.Replace method
string test = "902322\t\r\n900657\t\r\n10421\t\r\n";
string res = test.Replace("\t", String.Empty); // res is "902322\r\n900657\r\n10421\r\n"
Trim only removes the white spaces from the beginning and the end of the string. So because the first String ends with \r\n, which apparently aren't considered white spaces, Trim doesn't sees anything to remove. You can use Replace to replace the spaces and tabs from the string. For example:
test.Replace(" ", "").Replace("\t", "");
Trim() removes edge characters. It seems you want to remove characters anywhere in the string, which you can do by:
test.Replace("\t", null);
When you pass null as the replacement value, it simply removes the old value. From MSDN:
If newValue is null, all occurrences of oldValue are removed.
Also note that you can chain calls to Replace:
test = test.Replace("\t", null).Replace(" ", null);
How can I trim a string by a whole string instead of a list of single characters?
I want to remove all and whitespaces at beginning and end of an HTML string. But method String.Trim() does only have overloads for set of characters and not for set of strings.
You could use HttpUtility.HtmlDecode(String) and use the resultant as an input for String.Trim()
HttpUtility.HtmlDecode on MSDN
HttpServerUtility.HtmlDecode on MSDN (a wrapper you can access through the Page.Server property)
string stringWithNonBreakingSpaces;
string trimmedString = String.Trim(HttpUtility.HtmlDecode(stringWithNonBreakingSpaces));
Note: This solution would decode all the HTML strings in the input.
The Trim method removes from the current string all leading and trailing white-space characters by default.
Edit: Solution for your problem AFTER your edit:
string input = #" <a href='#'>link</a> ";
Regex regex = new Regex(#"^( |\s)*|( |\s)*$");
string result = regex.Replace(input, String.Empty);
This will remove all trailing and leading spaces and . You can add any string or character group to the expression. If you were to trim all tabs too the regex would simply become:
Regex regex = new Regex(#"^( |\s|\t)*|( |\s|\t)*$");
Not sure if this is what you're looking for?
string str = "hello ";
str.Replace(" ", "");
str.Trim();
Use RegEx, as David Heffernan said. It is rather easy to select all spaces at the start of string: ^(\ | )*
I'm trying to match on some inconsistently formatted HTML and need to strip out some double quotes.
Current:
<input type="hidden">
The Goal:
<input type=hidden>
This is wrong because I'm not escaping it properly:
s = s.Replace(""","");
This is wrong because there is not blank character character (to my knowledge):
s = s.Replace('"', '');
What is syntax / escape character combination for replacing double quotes with an empty string?
I think your first line would actually work but I think you need four quotation marks for a string containing a single one (in VB at least):
s = s.Replace("""", "")
for C# you'd have to escape the quotation mark using a backslash:
s = s.Replace("\"", "");
I didn't see my thoughts repeated already, so I will suggest that you look at string.Trim in the Microsoft documentation for C# you can add a character to be trimmed instead of simply trimming empty spaces:
string withQuotes = "\"hellow\"";
string withOutQotes = withQuotes.Trim('"');
should result in withOutQuotes being "hello" instead of ""hello""
s = s.Replace("\"", "");
You need to use the \ to escape the double quote character in a string.
You can use either of these:
s = s.Replace(#"""","");
s = s.Replace("\"","");
...but I do get curious as to why you would want to do that? I thought it was good practice to keep attribute values quoted?
s = s.Replace("\"",string.Empty);
c#: "\"", thus s.Replace("\"", "")
vb/vbs/vb.net: "" thus s.Replace("""", "")
If you only want to strip the quotes from the ends of the string (not the middle), and there is a chance that there can be spaces at either end of the string (i.e. parsing a CSV format file where there is a space after the commas), then you need to call the Trim function twice...for example:
string myStr = " \"sometext\""; //(notice the leading space)
myStr = myStr.Trim('"'); //(would leave the first quote: "sometext)
myStr = myStr.Trim().Trim('"'); //(would get what you want: sometext)
You have to escape the double quote with a backslash.
s = s.Replace("\"","");
s = s.Replace(#"""", "");
This worked for me
//Sentence has quotes
string nameSentence = "Take my name \"Wesley\" out of quotes";
//Get the index before the quotes`enter code here`
int begin = nameSentence.LastIndexOf("name") + "name".Length;
//Get the index after the quotes
int end = nameSentence.LastIndexOf("out");
//Get the part of the string with its quotes
string name = nameSentence.Substring(begin, end - begin);
//Remove its quotes
string newName = name.Replace("\"", "");
//Replace new name (without quotes) within original sentence
string updatedNameSentence = nameSentence.Replace(name, newName);
//Returns "Take my name Wesley out of quotes"
return updatedNameSentence;
s = s.Replace( """", "" )
Two quotes next to each other will function as the intended " character when inside a string.
if you would like to remove a single character i guess it's easier to simply read the arrays and skip that char and return the array. I use it when custom parsing vcard's json.
as it's bad json with "quoted" text identifiers.
Add the below method to a class containing your extension methods.
public static string Remove(this string text, char character)
{
var sb = new StringBuilder();
foreach (char c in text)
{
if (c != character)
sb.Append(c);
}
return sb.ToString();
}
you can then use this extension method:
var text= myString.Remove('"');