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: ^(\ | )*
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.
I wanna remove the -L from the end of my string if exists
So
ABCD => ABCD
ABCD-L => ABCD
at the moment I'm using something like the line below which uses the if/else type of arrangement in my Regex, however, I have a feeling that it should be way more easier than this.
var match = Regex.Match("...", #"(?(\S+-L$)\S+(?=-L)|\S+)");
How about just doing:
Regex rgx = new Regex("-L$");
string result = rgx.Replace("ABCD-L", "");
So basically: if the string ends with -L, replace that part with an empty string.
If you want to not only invoke the replacement at the end of the string, but also at the end of a word, you can add an additional switch to detect word boundaries (\b) in addition to the end of the string:
Regex rgx = new Regex("-L(\b|$)");
string result = rgx.Replace("ABCD-L ABCD ABCD-L", "");
Note that detecting word boundaries can be a little ambiguous. See here for a list of characters that are considered to be word characters in C#.
You also can use String.Replace() method to find a specific string inside a string and replace it with another string in this case with an empty string.
http://msdn.microsoft.com/en-us/library/fk49wtc1(v=vs.110).aspx
Use Regex.Replace function,
Regex.Replace(string, #"(\S+?)-L(?=\s|$)", "$1")
DEMO
Explanation:
( group and capture to \1:
\S+? non-whitespace (all but \n, \r, \t, \f,
and " ") (1 or more times)
) end of \1
-L '-L'
(?= look ahead to see if there is:
\s whitespace (\n, \r, \t, \f, and " ")
| OR
$ before an optional \n, and the end of
the string
) end of look-ahead
You certainly can use Regex for this, but why when using normal string functions is clearer?
Compare this:
text = text.EndsWith("-L")
? text.Substring(0, text.Length - "-L".Length)
: text;
to this:
text = Regex.Replace(text, #"(\S+?)-L(?=\s|$)", "$1");
Or better yet, define an extension method like this:
public static string RemoveIfEndsWith(this string text, string suffix)
{
return text.EndsWith(suffix)
? text.Substring(0, text.Length - suffix.Length)
: text;
}
Then your code can look like this:
text = text.RemoveIfEndsWith("-L");
Of course you can always define the extension method using the Regex. At least then your calling code looks a lot cleaner and is far more readable and maintainable.
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).
string myNumber = "3.44";
Regex regex1 = new Regex(".");
string[] substrings = regex1.Split(myNumber);
foreach (var substring in substrings)
{
Console.WriteLine("The string is : {0} and the length is {1}",substring, substring.Length);
}
Console.ReadLine();
I tried to split the string by ".", but it the splits return 4 empty string. Why?
. means "any character" in regular expressions. So don't split using a regex - split using String.Split:
string[] substrings = myNumber.Split('.');
If you really want to use a regex, you could use:
Regex regex1 = new Regex(#"\.");
The # makes it a verbatim string literal, to stop you from having to escape the backslash. The backslash within the string itself is an escape for the dot within the regex parser.
the easiest solution would be: string[] val = myNumber.Split('.');
. is a reserved character in regex. if you literally want to match a period, try:
Regex regex1 = new Regex(#"\.");
However, you're better off simply using myNumber.Split(".");
The dot matches a single character, without caring what that character
is. The only exception are newline characters.
Source: http://www.regular-expressions.info/dot.html
Therefore your implying in your code to split the string at each character.
Use this instead.
string substr = num.Split('.');
Keep it simple, use String.Split() method;
string[] substrings = myNumber.Split('.');
It has an other overload which allows specifying split options:
public string[] Split(
char[] separator,
StringSplitOptions options
)
You don't need regex you do that by using Split method of string object
string myNumber = "3.44";
String[] substrings = myNumber.Split(".");
foreach (var substring in substrings)
{
Console.WriteLine("The string is : {0} and the length is {1}",substring, substring.Length);
}
Console.ReadLine();
The period "." is being interpreted as any single character instead of a literal period.
Instead of using regular expressions you could just do:
string[] substrings = myNumber.Split(".");
In Regex patterns, the period character matches any single character. If you want the Regex to match the actual period character, you must escape it in the pattern, like so:
#"\."
Now, this case is somewhat simple for Regex matching; you could instead use String.Split() which will split based on the occurrence of one or more static strings or characters:
string[] substrings = myNumber.Split('.');
try
Regex regex1 = new Regex(#"\.");
EDIT: Er... I guess under a minute after Jon Skeet is not too bad, anyway...
You'll want to place an escape character before the "." - like this "\\."
"." in a regex matches any character, so if you pass 4 characters to a regex with only ".", it will return four empty strings. Check out this page for common operators.
Try
Regex regex1 = new Regex("[.]");
I convert a HTML code to plain text.But there are many extra returns and spaces.How to remove them?
string new_string = Regex.Replace(orig_string, #"\s", "") will remove all whitespace
string new_string = Regex.Replace(orig_string, #"\s+", " ") will just collapse multiple whitespaces into one
I'm assuming that you want to
find two or more consecutive spaces and replace them with a single space, and
find two or more consecutive newlines and replace them with a single newline.
If that's correct, then you could use
resultString = Regex.Replace(subjectString, #"( |\r?\n)\1+", "$1");
This keeps the original "type" of whitespace intact and also preserves Windows line endings correctly. If you also want to "condense" multiple tabs into one, use
resultString = Regex.Replace(subjectString, #"( |\t|\r?\n)\1+", "$1");
To condense a string of newlines and spaces (any number of each) into a single newline, use
resultString = Regex.Replace(subjectString, #"(?:(?:\r?\n)+ +){2,}", #"\n");
I used a lot of algorithm for that. Every loop was good but this was clear and absolute.
//define what you want to remove as char
char tb = (char)9; //Tab char ascii code
spc = (char)32; //space char ascii code
nwln = (char)10; //New line char ascii char
yourstring.Replace(tb,"");
yourstring.Replace(spc,"");
yourstring.Replace(nwln,"");
//by defining chars, result was better.
You can use Trim() to remove the spaces and returns. In HTML the spaces is not important so you can omit them by using the Trim() method in System.String class.