Replace special character with white space through regex - c#

I have a function which replace character.
public static string Replace(string value)
{
value = Regex.Replace(value, "[\n\r\t]", " ");
return value;
}
value="abc\nbcd abcd abcd\ " if in string there is any unwanted white space they are also remove.Means I want result like this
value="abcabcdabcd".Help to change Regex Pattern to get desire result.Thanks a lot.

If you need to remove any number of whitespace characters from the string, probably you're looking for something like this:
value = Regex.Replace(value, #"\s+", "");
where \s matches any whitespace character and + means one or more times.

Instead of replacing your newline, tab, etc. characters with a space, just replace all whitespace with nothing:
public static string RemoveWhitespace(string value)
{
return Regex.Replace(value, "\\s", "");
}
\s is a special character group that matches all whitespace characters. (The backslash is doubled because the backslash has a special meaning in C# strings as well.) The following MSDN link contains the exact definition of that character group:
Character Classes: White-Space Character: \s

You may want to try \s indicating white spaces. With the statement Regex.Replace(value, #"\s", ""), the output will be "abcabcdabcd".

Related

Getting the substring after a character in C# using regex

I have the following input string:
string val = "[01/02/70]\nhello world ";
I want to get the all words after the last ] character.
Example output for a sample string above:
\nhello world
In C#, use Substring() with IndexOf:
string val = val.Substring(val.IndexOf(']') + 1);
If you have multiple ] symbols, and you want to get all the string after the last one, use LastIndexOf:
string val = "[01/02/70]\nhello [01/02/80] world ";
string val = val.Substring(val.LastIndexOf(']') + 1); // => " world "
If you are a fan of Regex, you might want to use a Regex.Replace like
string val = "[01/02/70]\nhello [01/02/80] world ";
val = Regex.Replace(val, #"^.*\]", string.Empty, RegexOptions.Singleline); // => " world "
See demo
Notes on REGEX:
RegexOptions.Singleline makes . match a linebreak
^ - matches beginning of string
.* - matches 0 or more characters but as many as possible (greedy matching)
\] - matches literal ] (as it is a special regex metacharacter, it must be escaped).
You need to use lookbehind assertion. And not only that, you have to enable DOTALL modifier also, so that it would also match the newline character present inbetween.
"(?s)(?<=\\]).*"
(?s) - DOTALL modifier.
(?<=\\]) - lookbehind which asserts that the match must be preceeded by a close bracket
.* - Matches any chracater zero or more times.
or
"(?s)(?<=\\])[\\s\\S]*"
Try this if you don't want to match the following newline character.
#"(?<=\][\n\r]*).*"

Regex replace Windows line break characters

I have this bit of code, which is supposed to replace the Windows linebreak character (\r\n) with an empty character.
However, it does not seem to replace anything, as if I view the string after the regex expression is applied to it, the linebreak characters are still there.
private void SetLocationsAddressOrGPSLocation(Location location, string locationString)
{
//Regex check for the characters a-z|A-Z.
//Remove any \r\n characters (Windows Newline characters)
locationString = Regex.Replace(locationString, #"[\\r\\n]", "");
int test = Regex.Matches(locationString, #"[\\r\\n]").Count; //Curiously, this outputs 0
int characterCount = Regex.Matches(locationString,#"[a-zA-Z]").Count;
//If there were characters, set the location's address to the locationString
if (characterCount > 0)
{
location.address = locationString;
}
//Otherwise, set the location's coordinates to the locationString.
else
{
location.coordinates = locationString;
}
} //End void SetLocationsAddressOrGPSLocation()
You are using verbatim string literal, thus \\ is treated as a literal \.
So, your regex is actually matching \, r and n.
Use
locationString = Regex.Replace(locationString, #"[\r\n]+", "");
This [\r\n]+ pattern will make sure you will remove each and every \r and \n symbol, and you won't have to worry if you have a mix of newline characters in your file. (Sometimes, I have both \n and \r\n endings in text files).

Disallow whitespaces in regex

I have this code:
private static bool IsTextAllowed(string text)
{
Regex regex = new Regex("[^0-9]+"); // Regex that matches disallowed text
return !regex.IsMatch(text);
}
private void TextboxClientID_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = !IsTextAllowed(e.Text);
}
This allows whitespaces in the textbox, how to prevent from inserting whitespaces too?
In regex, the \s modifier translates to [\r\n\t\f ], which means no newline characters, no tab characters, no form feed characters (used by printers to start a new page), and no spaces.
So you can use the regex [^\\s] (you have to use \\ in order to make a single \, which will then translate to \s finally. If you just use \s, it will translate to s character literal.
The beginning and ending ^ and $ characters match the beginning and end of the string respectively.
So, you could use the regex ^[^0-9\\s]+$. Here is a breakdown of what it does:
The first ^ matches the beginning of the string.
Next, we have the group inclosed in [], which will match any single character in that group
Inside of the [], we have ^0-9\\s:
The ^ character makes sure that no single character inside of the [] will be matched (switches it from any single character to no single character), none of the following should be true
The 0-9 part matches any number between 0 and 9
The \\s part creates literally \s. \s matches any whitespace character
The + matches the group inclosed in [] between 1 and infinite times
The final $ matches the end of the string
Your code could be:
private static bool IsTextAllowed(string text){
Regex regex = new Regex("^[^0-9\\s]+$");
return !regex.IsMatch(text);
}
Here's a regex101 test: https://regex101.com/r/aS9xT0
^[^0-9 ]+$
Try this.This will not allow whitespaces at all.
*NOT a regex answer, I had the same issue with the space char's
I fixed this by adding PreviewKeyDown on the TextBox and setting e.Handled to true if spacebar has been pressed, just like this:
private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
e.Handled = e.Key == Key.Space;
}
Use:
#"^[^\d\s]+$"
\d ... Match a digit (0-9).
\s ... Match a whitespace character.
private static bool IsTextAllowed(string text)
{
return Regex.IsMatch(text, #"^[^\d\s]+$");
}
Why do you bother with regex ? Simply use:
private static bool IsTextAllowed(string text)
{
return text.All(c => !char.IsWhiteSpace(c));
}
Old question.. But to disallow whitespaces use the "Any non-whitespace character" \S coupled with a multiplier +. It will match basically anything, even '∆', but no whitespaces (\n, \r, \t, \f, \v)
\S+
But a number input without whitespace can simply be, as #vks mentioned;
^[0-9]+$

Trim Non-alphanum from beginning and end of string

what is the best way to trim ALL non alpha numeric characters from the beginning and end of a string ? I tried to add characters that I do no need manually but it doesn't work well and use the . I just need to trim anything not alphanumeric.
I tried using this function:
string something = "()&*1#^#47*^#21%Littering aaaannnndóú(*&^1#*32%#**)7(#9&^";
string somethingNew = Regex.Replace(something, #"[^\p{L}-\s]+", "");
But it removes all characters that are non alpha numeric from the string. What I basically want is like this:
"test1" -> test1
#!#!2test# -> 2test
(test3) -> test3
##test4---- -> test4
I do want to support unicode characters but not symbols..
EDIT:
The output of the example should be:
Littering aaaannnndóú
Regards
Assuming you want to trim non-alphanumeric characters from the start and end of your string:
s = new string(s.SkipWhile(c => !char.IsLetterOrDigit(c))
.TakeWhile(char.IsLetterOrDigit)
.ToArray());
#"[^\p{L}\s-]+(test\d*)|(test\d*)[^\p{L}\s-]+","$1"
You can use String function String.Trim Method (Char[]) in .NET library to trim the unnecessary characters from the given string.
From MSDN : String.Trim Method (Char[])
Removes all leading and trailing occurrences of a set of characters
specified in an array from the current String object.
Before trimming the unwanted characters, you need to first identify whether the character is Letter Or Digit, if it is non-alphanumeric then you can use String.Trim Method (Char[]) function to remove it.
you need to use Char.IsLetterOrDigit() function to identify wether the character is alphanumeric or not.
From MSDN: Char.IsLetterOrDigit()
Indicates whether a Unicode character is categorized as a letter or a
decimal digit.
Try This:
string str = "()&*1#^#47*^#21%Littering aaaannnndóú(*&^1#*32%#**)7(#9&^";
foreach (char ch in str)
{
if (!char.IsLetterOrDigit(ch))
str = str.Trim(ch);
}
Output:
1#^#47*^#21%Littering aaaannnndóú(*&^1#*32%#**)7(#9
If you need to remove any character which is not alphanumeric, you can use IsLetterOrDigit paired with a Where to go through every character. And because we're working at the char level, we'll need a little Concat at the end to bring everything back into a string.
string result = string.Concat(input.Where(char.IsLetterOrDigit));
which you can easily convert into an extension method
public static class Extensions
{
public static string ToAlphaNum(this string input)
{
return string.Concat(input.Where(char.IsLetterOrDigit));
}
}
that you can use like this :
string testString = "#!#!\"(test123)\"";
string result = testString.ToAlphaNum(); //test123
Note: this will remove every non-alphanumeric character from your string, if you really need to remove only those at the beginning/end, please add more details about what defines a beginning or an end and add more examples.
And you could also replace all the non-letters/numbers at the beginning and/or end of the line:
^[^\p{L}\p{N}]*|[^\p{L}\p{N}]*$
used as
resultString = Regex.Replace(subjectString, #"^[^\p{L}\p{N}]*|[^\p{L}\p{N}]*$", "", RegexOptions.Multiline);
If you really want to only remove characters at the beginning and end of the "String" and not do this line by line, then remove the ^$ match at linebreak option (RegexOption.Multiline)
If you wanted to include leading or trailing underscores, as characters to be retained, you could simplify the regex to:
^\W+|\W+$
The core of the regex:
[^\p{L}\p{N}]
is a negated character class which includes all of the characters in the Unicode class of Letters \p{L} or Numbers \p{N}
In other words:
Trim non-unicode alphanumeric characters
^[^\p{L}\p{N}]*|[^\p{L}\p{N}]*$
Options: Case sensitive; Exact spacing; Dot doesn't match line breaks; ^$ match at line breaks; Parentheses capture
Match this alternative «^[^\p{L}\p{N}]*»
Assert position at the beginning of a line «^»
Match any single character NOT present in the list below «[^\p{L}\p{N}]*»
Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
A character from the Unicode category “letter” «\p{L}»
A character from the Unicode category “number” «\p{N}»
Or match this alternative «[^\p{L}\p{N}]*$»
Match any single character NOT present in the list below «[^\p{L}\p{N}]*»
Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
A character from the Unicode category “letter” «\p{L}»
A character from the Unicode category “number” «\p{N}»
Assert position at the end of a line «$»
Created with RegexBuddy
Without using regex:
In Java, you could do: (in c# syntax would be nearly the same with same functionality)
while (true) {
if (word.length() == 0) {
return ""; // bad
}
if (!Character.isLetter(word.charAt(0))) {
word = word.substring(1);
continue; // so we are doing front first
}
if (!Character.isLetter(word.charAt(word.length()-1))) {
word = word.substring(0, word.length()-1);
continue; // then we are doing end
}
break; // if front is done, and end is done
}
you could use this pattern
^[^[:alnum:]]+|[^[:alnum:]]+$
with g option
Demo

RegEx.Replace to Replace Whole Words and Skip when Part of the Word

I am using regex to replace certain keywords from a string (or Stringbuilder) with the ones that I choose. However, I fail to build a valid regex pattern to replace only whole words.
For example, if I have InputString = "fox foxy" and want to replace "fox" with "dog" it the output would be "dog dogy".
What is the valid RegEx pattern to take only "fox" and leave "foxy"?
public string Replace(string KeywordToReplace, string Replacement) /
{
this.Replacement = Replacement;
this.KeywordToReplace = KeywordToReplace;
Regex RegExHelper = new Regex(KeywordToReplace, RegexOptions.IgnoreCase);
string Output = RegExHelper.Replace(InputString, Replacement);
return Output;
}
Thanks!
Regexes support a special escape sequence that represents a word boundary. Word-characters are everything in [a-zA-Z0-9]. So a word-boundary is between any character that belongs in this group and a character that doesn't. The escape sequence is \b:
\bfox\b
Do not forget to put '#' symbol before your '\bword\b'.
For example:
address = Regex.Replace(address, #"\bNE\b", "Northeast");
# symbol ensures escape character, backslash(\), does not get escaped!
You need to use boundary..
KeywordToReplace="\byourWord\b"

Categories

Resources