I want to strip off everything but numbers, $, comma(,).
this only strip letters
string Cadena;
Cadena = tbpatronpos6.Text;
Cadena = Regex.Replace(Cadena, "([^0-9]|\\$|,)", "");
tbpatronpos6.Text = Cadena;
Why doesn't my regex work, and how can I fix it?
I suspect this is what you want:
using System;
using System.Text.RegularExpressions;
class Test
{
static void Main(string[] args)
{
string original = #"abc%^&123$\|a,sd";
string replaced = Regex.Replace(original, #"[^0-9$,]", "");
Console.WriteLine(replaced); // Prints 123$,
}
}
The problem was your use of the alternation operator, basically - you just want the set negation for all of (digits, comma, dollar).
Note that you don't need to escape the dollar within a character group.
you want something like this?
[^\\d\\$,]
Related
I am trying to write "text" into a file with
private void WriteToLogs(string text)
{
File.AppendAllText(todayMessageLog, $"({DateTime.Now}) Server Page: \"{text.Trim()}\"\n");
}
The text comes out as this:
"text (a bunch of white space)"
The text string is made up of these:
string username = e.NewClientUsername.Trim().Replace(" ", "");
string ip = e.NewClientIP.Trim().Replace(" ", "");
WriteToLogs($"{username.Trim().Replace(" ", "")} ({ip.Trim().Replace(" ", "")}) connected"); // NONE OF THESE WORKED FOR REMOVING THE WHITE SPACE
The "e" parameter comes from a custom EventArgs class in another namespace and NewClientIP and NewClientUsername are properties inside the class
As you can see, I tried with both Trim and Replace on both the strings themselves and the method but nothing removes the white space.
If the Trim() and Replace() methods do not work, the string is likely not padded with the usual white-space characters like SPACE or TAB, but something else. There are many other characters which can show up blank.
Try printing the result with something like BitConverter.ToString(Text.Encoding.UTF8.GetBytes(text)). Spaces would show up as 20-20-20-..., but you will probably get something else.
The white space shows up as 00, not 20, how can I remove it?
Good. Use the argument to the Trim() method, like so:
var text = "Blah\0\0\0\0";
text.Length → 8
text.Trim('\0').Length → 4
I hope that this working for you
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
//This is your text
string input = "This is text with far too much "+
"This is text with far too much "+
"This is text with far too much ";
//This is the Regex
string pattern = "\\s";
//Value with the replace
string replacement = "";
//Replace
string result = Regex.Replace(input, pattern, replacement);
//Result
Console.WriteLine("Original String: {0}", input);
Console.WriteLine("Replacement String: {0}", result);
}
}
If you want to trim white spaces (not only ' ', but \t, \U00A0 etc.) as well as \0 (which is not white space), you can try regular expressions:
using System.Text.RegularExpressions;
...
// Trim whitespaces and \0
string result = Regex.Replace(input, #"(^[\s\0]+)|([\s\0]+$)", "");
For reference
// Trim start whitespaces and \0
string resultStart = Regex.Replace(input, #"^[\s\0]+", "");
// Trim end whitespaces and \0
string resultEnd = Regex.Replace(input, #"[\s\0]+$", "");
Same idea (regular expressions), but different pattern if you want not to trim but remove white spaces and \0:
string result = Regex.Replace(input, #"[\s\0]+", "");
I came across How to search and replace exact matching strings only. However, it doesn't work when there are words that start with #. My fiddle here https://dotnetfiddle.net/9kgW4h
string textToFind = string.Format(#"\b{0}\b", "#bob");
Console.WriteLine(Regex.Replace("#bob!", textToFind, "me"));// "#bob!" instead of "me!"
Also, in addition to that what I would like to do is that, if a word starts with \# say for example \#myname and if I try to find and replace #myname, it shouldn't do the replace.
I suggest replacing the leading and trailing word boundaries with unambiguous lookaround-based boundaries that will require whitespace chars or start/end of string on both ends of the search word, (?<!\S) and (?!\S). Besides, you need to use $$ in the replacement pattern to replace with a literal $.
I suggest:
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string text = #"It is #google.com or #google w#google \#google \\#google";
string result = SafeReplace(text,"#google", "some domain", true);
Console.WriteLine(result);
}
public static string SafeReplace(string input, string find, string replace, bool matchWholeWord)
{
string textToFind = matchWholeWord ? string.Format(#"(?<!\S){0}(?!\S)", Regex.Escape(find)) : find;
return Regex.Replace(input, textToFind, replace.Replace("$","$$"));
}
}
See the C# demo.
The Regex.Escape(find) is only necessary if you expect special regex metacharacters in the find variable value.
The regex demo is available at regexstorm.net.
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 need to extract a substring from an existing string. This String starts with uninteresting characters (include "," "space" and numbers) and ends with ", 123," or ", 57," or something like this where the numbers can change. I only need the Numbers.
Thanks
public static void Main(string[] args)
{
string input = "This is 2 much junk, 123,";
var match = Regex.Match(input, #"(\d*),$"); // Ends with at least one digit
// followed by comma,
// grab the digits.
if(match.Success)
Console.WriteLine(match.Groups[1]); // Prints '123'
}
Regex to match numbers: Regex regex = new Regex(#"\d+");
Source (slightly modified): Regex for numbers only
I think this is what you're looking for:
Remove all non numeric characters from a string using Regex
using System.Text.RegularExpressions;
...
string newString = Regex.Replace(oldString, "[^.0-9]", "");
(If you don't want to allow the decimal delimiter in the final result, remove the . from the regular expression above).
Try something like this :
String numbers = new String(yourString.TakeWhile(x => char.IsNumber(x)).ToArray());
You can use \d+ to match all digits within a given string
So your code would be
var lst=Regex.Matches(inp,reg)
.Cast<Match>()
.Select(x=x.Value);
lst now contain all the numbers
But if your input would be same as provided in your question you don't need regex
input.Substring(input.LastIndexOf(", "),input.LastIndexOf(","));
I have a string containg alphabetic characters, for example:
254.69 meters
26.56 cm
23.36 inches
100.85 ft
I want to remove all the alphabetic characters (units) from the above mentioned strings so that I can call the double.Parse() method.
This should work:
// add directive at the top
using System.Text.RegularExpressions;
string numberOnly = Regex.Replace(s, "[^0-9.]", "")
You should be able to solve this using Regex. Add the following reference to your project:
using System.Text.RegularExpressions;
after that you can use the following:
string value = Regex.Replace(<yourString>, "[A-Za-z ]", "");
double parsedValue = double.Parse(value);
Assuming you have only alphabetic characters and space as units.
Using LINQ:
using System.Linq;
string input ="57.20000 KG ";
string output = new string(input.Where(c=>(Char.IsDigit(c)||c=='.'||c==',')).ToArray());
Hi another solution is:
// add directive at the top
using System.Text.RegularExpressions;
string s = "24,99";
string numberOnly = Regex.Replace(s, "[^0-9,-]+", "")
This solution will not remove the dot e.g. question from user1804084:
this remove the dot for me e.g. 24.99 somechracter -> 2499
However it can still be convertet to a double where adding and subtraction works as normal.
The Regex, and Vlad's LINQ answers cover the solution well. And are both good options.
I had a similar problem, but I also wanted to only explicitly strip letters, and not to strip white space or etc, with this variant.
I also wanted it usable as below. Any of the other solutions could be packaged in a similar manner.
public static string StripAlpha(this string self)
{
return new string( self.Where(c => !Char.IsLetter(c)).ToArray() );
}
public static string StripNonNumeric(this string self)
{
// Use Vlad's LINQ or the Regex Example
return new string(self.Where(c=>(Char.IsDigit(c)||c=='.'||c==',')).ToArray()) ; // See Vlad's
}
This would then be used such as:
var newString = someString.StripAlpha();
var newString2 = someString.StripNonNumeric();
Use CharMatcher API from Google's Guava library:
String magnitudeWithUnit = "254.69 meter";
String magnitude = CharMatcher.inRange('a', 'z').or(inRange('A', 'Z')).removeFrom(magnitudeWithUnit);
Do static-import CharMatcher.inRange(..). You can trim the results for trailing space.