C# How to trim both whitespace character and other character [duplicate] - c#

This question already has answers here:
Fastest way to remove the leading special characters in string in c#
(2 answers)
Closed 8 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
I want to trim leading whitespace and the single quote using one call to Trim without calling it twice as follows.
string s = " 'hello'";
var newString = s.Trim().Trim('\'');
I don't want to use
var newString = s.TrimStart().Trim(''\').
either as it is two calls.

Use the overload of Trim that accepts multiple characters:
string s = " 'hello'";
var newString = s.Trim(' ', '\'');
Although there are several caveats:
your question only mentions leading whitespace, but Trim removes trailing characters as well. If you only want leading characters use TrimStart instead.
this solution only removes full spaces, not all whitespace. Technically you would have to add all characters that are considered "whitespace". If you need to trim more than just spaces, then calling Trim twice will be cleaner.
This solution would also Trim whitespace within the apostrophes:
string s = " ' hello'";
var newString = s.Trim(' ', '\''); // returns "hello"

Related

How to Split string but keep delimiter at the start [duplicate]

This question already has answers here:
How to split string with Regex.Split and keep all separators?
(2 answers)
Closed 2 years ago.
I was wondering how to Split a string in C# but keeping the delimiters at the start of each substring.
Example:
Input: "1,2,3,4,5,6"
Delimiter: ','
Output: {'1', ',2', ',3', ',4', ',5', ',6'}
At the moment I only know to keep the delimiter at the end of each substring using Regex.Split from this answer.
String text = "1,2,3,4,5,6";
var split = Regex.Split(text, #"(?<=,)");
Instead of lookbehind you need to use a lookahead for splitting:
(?=,)
RegEx Demo
What you want is splitting on a position when you have comma at next position that makes it a lookahead assertion. On the other hand a lookbehind assertion will split when we have comma at previous position thus splitting after comma not before it.
Code:
String text = "1,2,3,4,5,6";
var split = Regex.Split(text, #"(?=,)");
//=> ["1", ",2", ",3", ",4", ",5", ",6"]

Why is my regex not escaping this backslash? [duplicate]

This question already has answers here:
C# Regex Issue "unrecognized escape sequence"
(3 answers)
Regular expression to allow backslash in C#
(3 answers)
Closed 3 years ago.
I am looking to create a list of file inside a folder, all matching a regex.
But the regex crash whenever I put a path containing backslash inside the regex.
string test = #"C:\TEMP"; // or "C:\\TEMP"
Regex reg = new Regex(test + "\\" + "tstNL02" + #"_(.*).csv"); // it crash here
FileList = Directory.GetFiles(test).Where(path => reg.IsMatch(path)).ToList();
ArgumentException: parsing "C:\TEMP\tstNL02_(.*).csv" - Unrecognized escape sequence \T.
As far as I know, using a # or escaping the backslash should prevent the regex from interpreting backslashes in a string as an escaping character (and if I remove test from the regex but leave the \\, regex doesn't crash).
If I put #"C:\\TEMP" the Regex doesn't parse any and the match fail C:\\TEMP\tstNL02_(.*).csv
I fixed my problem by going another way but I was wondering why and how to fix this backslash-in-a-variable thing ?
Edit: problem didn't came from regex but from the fact I was using the same string for regex and Directory.GetFiles. Adding escaping backslashes to the string so Regex worked correctly would cause Directory.GetFiles to not escape those added backslashes, thus not matching files

C# .NET Regex 'Unrecognized escape sequence' [duplicate]

This question already has answers here:
Unrecognized escape sequence for path string containing backslashes
(5 answers)
Closed 7 years ago.
I'm trying to validate a password field using regex under the namespace System.Text.RegularExpressions but I'm getting three errors for
'Unrecognized escape sequence'.
When I double click on the errors it highlights the '-' in my expression for the character range but I don't know why this is wrong.
// password must contain one uppercase, one lowercase and one digit
Regex reg = new Regex("^(?=.*[!##$%^&*()\-_=+`~\[\]{}?|])(?=.+[a-z])(?=.+[A-Z])(? =.+[0-9]).{8,50}$");
Just add an # before the first quote to make it a verbatim string literal or escape the backslashes as \\.
it seems you have one space after ?
(? =.+[0-9]).{8,50}
remove that.

Remove last "X" characters from string [duplicate]

This question already has answers here:
How to remove the last comma and space from string (if there) using regex?
(4 answers)
Closed 7 years ago.
I have a string that can end will several "X" characters.
Let's say the string ends in commas like this.
string X = "1,2,3,,,";
I need some function or lambda expression that can remove the last set of commas.
I will have no way of knowing how many commas there are at the end of the string but the end result should look like this.
?x -- "1,2,3";
You dont need regex or LINQ, use String.TrimEnd:
X = X.TrimEnd(',');
You can use it with multiple characters, f.e. if you want to remove trailing commas and dots:
X = X.TrimEnd(',', '.');

What is a verbatim string? [duplicate]

This question already has answers here:
What is the difference between a regular string and a verbatim string?
(6 answers)
Closed 9 years ago.
From ReSharper, I know that
var v = #"something";
makes v something called a verbatim string. What is this and what is a common scenario to use it?
In a verbatim string, escape sequences (such as "\n" for newline) will be ignored. This helps you type strings containing backslashes.
The string is also allowed to extend over multiple lines, for example:
var s = #"
line1
line2";
The string will appear the same way you typed it in your source code, with line breaks, so you don't have to worry about indents, newlines etc.
To use quotes inside a verbatim literal, you just double them:
#"This is a string with ""quotes""."
It means that special chars don't need to be escaped, since you informed the compiler to expect special characters, and to ignore them. A common use case might be to specify a connection string:
string sqlServer = #"SERVER01\SQL";
This is perfectly valid, as opposed to in normal use where the backslash would be considered an escape character.

Categories