Removing White spaces from string is not working in c# [duplicate] - c#

This question already has answers here:
How do I replace multiple spaces with a single space in C#?
(28 answers)
Closed 6 years ago.
I am trying to remove whitespaces from string but it is not working
string status = " 18820 Pacific Coast Highway
Malibu, CA 90265";
string status1 = status.Trim();
Console.Write(status1);
The above code is not working
Expected Output:
18820 Pacific Coast Highway Malibu, CA 90265

Trim removes leading and trailing symbols (spaces by default). Use Regular expression instead.
RegEx.Replace(status, "\s+", " ").Trim();

Trim() only works at the start and end of a string. This should work:
string status1 = Regex.Replace(status,#"\s+"," ").Trim();

string status = " 18820 Pacific Coast Highway
Malibu, CA 90265";
string status1 = status.Trim();
Console.Write(status1);
status = status .Replace(" ", "");
But the above code will remove all the whitespaces.
If you want to have whitespace at the end of everyword, then use foreach as mentioned in this link
How to trim whitespace between characters

Related

Extract DateTime from string

When looping through elements in a List<string> I want to extract the first date time.
This is a sample line where in this case month is a single digit, month can also be a double digit e.g. 12 but not say 01.
string line = "\\\\SomeServer\\HTTP\\demo1\\index.cfm 4 KB CFM " +
"File 2/19/2019 3:48:21 PM " +
"2/19/2019 1:05:53 PM 2/19/2019 1:05:53 PM 5";
The expected result would be
2/19/2019 3:48:21 PM
I have looked at various regular expression code sample here, the following is one which properly handles single digit months only and does not return the time portion for the date (as I don't know what pattern to use).
var line = "\\\\SomeServer\\HTTP\\FolderName\\index.cfm 4 KB CFM " +
"File 02/19/2019 3:48:21 PM " +
"2/19/2019 1:05:53 PM 2/19/2019 1:05:53 PM 5";
var match = Regex.Match(line,
#"\d{2}\/\d{2}\/\d{4}");
var dateValue = match.Value;
if (!string.IsNullOrWhiteSpace(dateValue))
{
var dateTime = DateTime.ParseExact(dateValue,
"MM/dd/yyyy",
CultureInfo.CurrentCulture);
Console.WriteLine(
dateTime.ToString(CultureInfo.InvariantCulture));
}
In closing, I've looked at recommended question lite up when posting this question and have virtually no expertise creating regular expressions. I appreciate any recommendations and/or code samples to get me in the right direction.
You may use
\b\d{1,2}/\d{1,2}/\d{4}\s\d{1,2}:\d{2}:\d{2}\s?[AP]M\b
See the regex demo. The Regex.Match will get you the first match.
Details
\b - word boundary
\d{1,2}/\d{1,2}/\d{4} - one or two digits, /, one or two digits, /, four digits
\s - a whitespace
\d{1,2}:\d{2}:\d{2} - 1 or 2 digits, :, 2 digits, :, 2 digits
\s? - an optional whitespace
[AP]M - AM or PM
\b - word boundary.

c# regex won't match newline [duplicate]

This question already has answers here:
C# Regex Match between with or without new lines
(2 answers)
How do I match any character across multiple lines in a regular expression?
(26 answers)
Closed 4 years ago.
I am trying to use a regex in c# to parse a multi line file ( Currently just in a string ) And this part seems to be where the problem is (.*?\n) it will split the .v/L1 and .v/L2 however when I put a nl between it fails the input file will look something like this.
MSG
.v/1L
.v/2L
.some other data
.and so on
ENDMSG
And this is part of the c# code
string nl = new string(new char[] { '\u000A' });
string pattern = #"(?<group>((?<type>MSG\n)(.*?\n)(?<end>ENDMSG\n)))";
string input = #" MSG" + nl + ".v/1L.v/2L" + nl + "ENDMSG" + nl;
// The Line below doesn't work
//string input = #" MSG" +nl+ ".v/1L" +nl+ ".v/2L" +nl+ "ENDMSG" + nl;
RegexOptions options = RegexOptions.Multiline;
foreach (Match m in Regex.Matches(input, pattern, options))
{
Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
}
And this is the output of the one that works:
Starting RegEx !
RegEx : (?<group>((?<type>MSG\n)(.*?\n)(?<end>ENDMSG\n)))
'MSG
.v/1L.v/2L << Should be split into 2 when adding a \n between
ENDMSG
' found at index 1.
Executing finally block.
If you specify RegexOptions.Multiline then you can use ^ and $ to match the start and end of a line, respectively.
If you don't wish to use this option, remember that a new line may be any one of the following: \n, \r, \r\n, so instead of looking only for \n, you should perhaps use something like: [\n\r]+, or more exactly: (\n|\r|\r\n).

How to sanitize a string removing specific character? [duplicate]

This question already has answers here:
Is there a simple way to remove multiple spaces in a string?
(26 answers)
How do I replace multiple spaces with a single space in C#?
(28 answers)
Closed 4 years ago.
I have this string:
PO Box 162, Ferny Hills
QLD 4055
Brisbane
which contains these character:
I want remove this charactes, so I tried:
info.Address = dd[i].InnerText
.Replace("\n", " ")
.Replace(" ", "")
.Replace(",", ", ");
but didn't works, I get all the character of the string attached. I'm expecting this result: PO Box 162, Ferny Hills QLD 4055 Brisbane.
Well, you replaced all blanks by nothing ( .Replace(" ", "") ). What did you expect? Now all your blanks are gone.
If you don't want that, don't do it.
you can try like this, by splitting and trimming the string to remove spaces and join them back by newline
var address = dd[i].InnerText.Split(new[] { Environment.NewLine })
.Select(s => s.Trim());
info.Address = String.Join(Environment.NewLine, address);

parse value from given string using Regex [duplicate]

This question already has an answer here:
C# verbatim string literal not working. Very Strange backslash always double
(1 answer)
Closed 6 years ago.
I have this string:
String str = "Displaying bills 1 - 20 of 10000 in total";
And i want to parse the total value, 10000 in this case.
This is what i have try:
Regex regex = new Regex(#"\\d+(?=\\s*in total)");
Match match = regex.Match("Displaying bills 1 - 20 of 10000 in total");
if (match.Success)
{
Console.WriteLine(match.Value);
}
And currently this now succeed.
string text = "Displaying bills 1 - 20 of 10000 in total";
Regex r = new Regex(Regex.Escape("of") +"(.*?)"+Regex.Escape("in"));
MatchCollection matches = r.Matches(text);
MessageBox.Show(matches[0].Groups[1].Value);
As mentioned in comment by #juharr, you just need to remove the double backslashes. The # at the beginning of the string marks it as a verbatim string, which doesn't require special characters to be escaped.

Replace special characters or special characters followed by space

I have this particular string:
Administrationsomkostninger I -2.889 - r0.l l0
I would like to replace these characters:r,l and i with 1.
I use this expression:
([(t|r|l|i|)])
That gives me this string:
Adm1n1s11a11onsomkos1n1nge1 1 -2.889 - 10.1 10
Now i want to replace the all digits that contains a digit followed + a whitespace
so in this case only - 10.1 10 gets converted to -10.110
Try this
string input = "Administrationsomkostninger I -2.889 - r0.l l0";
string pattern = #"(?'spaces'\s){2,}";
string output = Regex.Replace(input, pattern, " ");
​

Categories