How to to remove characters from numeric value using regex - c#

I have the value 4,59,999/-. My code is
if (Regex.IsMatch(s,#"\b[1-9]\d*(?:,[0-9]+)*/?-?"))
{
string value = Regex.Replace(s, #"[^\d]", " ");
textBox2.Text= value;
}
Output is: 4 59 999, I need it to be 459999 (without "," , "/" , "-" and " ").

How about without regex?
var s = "4,59,999/-";
var array = s.Where(c => char.IsDigit(c)).ToArray();
or shorter
var array = s.Where(char.IsDigit).ToArray();
And you can use this array in a string(Char[]) constructor.
var result = new string(array); // 459999

You don't need regex, you could use:
textBox2.Text = String.Concat(s.Where(Char.IsDigit));
Much better is to use decimal.Parse/TryParse:
string s = "4,59,999/-.";
decimal price;
if (decimal.TryParse(s.Split('/')[0], NumberStyles.Currency, NumberFormatInfo.InvariantInfo, out price))
textBox2.Text = price.ToString("G");

Just replace with empty string.
string value = Regex.Replace(s, #"[^\d]", ""); // See the change in the replace string.
textBox2.Text= value;
Note You don't require the if as the regex replace will work only if there is a match for non digits ([^\d])

Should just be a case of replacing it with an empty string instead of a space?
Regex.Replace(s, #"[^\d]", String.Empty);

Currently you're replacing these characters with a space. Use an empty set of quotes instead.
if (Regex.IsMatch(s,#"\b[1-9]\d*(?:,[0-9]+)*/?-?"))
{
string value = Regex.Replace(s, #"[^\d]", "");
textBox2.Text= value;
}

You are replacing the ",", "/", "-" and " " with a white space. Try this instead:
string value = Regex.Replace(s, #"[^\d]", "");
Hope this helps.

Linq is a possible solution:
String s = "4,59,999/-";
...
textBox2.Text = new String(s.Where(item => item >= '0' && item <= '9').ToArray());

Try something like this it will work 100% in php so just change some syntax for C#
<?php
$str = "4,59,999/-.";
echo $str = preg_replace('/[^a-z0-9]/', '', $str);
?>

Related

replace matching special characters pattern from a string

string s = "apple]","[banana...." ;
I need to remove ( "]","[ ) and replace with "," from above string so that the output looks like below:
s = "apple,banana...."
s = s.Replace(#"\]","[\", ","); //something like this?
You need to escape the quotation marks in the string. You have tried to escape something, but \ isn't used to escape characters in a # delimited string.
In a # delimited string you use "" to escape ":
s = s.Replace(#"]"",""[", ",");
In a regular string you use \" to escape ":
s = s.Replace("]\",\"[", ",");
I assume it is a string[]?
I propose something like this:
string[] s = {"[apple]","[banana]","[orange]"} ;
string new_s = "";
foreach (string ss in s)
{
new_s += ss.Replace("[", "").Replace("]", ",");
}
//handle extra "," at end of string
new_s = new_s.Remove(new_s.Length-1);
Edit: Disregard, I misunderstood what you were trying to accomplish due to syntactical errors in your string definition.
string s = "apple]","[banana...." ;
should be:
string s = "apple]\",\"[banana....";

Extract some numbers and decimals from a string

I have a string:
" a.1.2.3 #4567 "
and I want to reduce that to just "1.2.3".
Currently using Substring() and Remove(), but that breaks if there ends up being more numbers after the pound sign.
What's the best way to go about doing this? I've read a bunch of questions on regex & string.split, but I can't get anything I try to work in VB.net. Would I have to do a match then replace using the match result?
Any help would be much appreciated.
This should work:
string input = " a.1.2.3 #4567 ";
int poundIndex = input.IndexOf("#");
if(poundIndex >= 0)
{
string relevantPart = input.Substring(0, poundIndex).Trim();
IEnumerable<Char> numPart = relevantPart.SkipWhile(c => !Char.IsDigit(c));
string result = new string(numPart.ToArray());
}
Demo
Try this...
String[] splited = split("#");
String output = splited[0].subString(2); // 1 is the index of the "." after "a" considering there are no blank spaces before it..
Here is regex way of doing it
string input = " a.1.2.3 #4567 ";
Regex regex = new Regex(#"(\d\.)+\d");
var match = regex.Match(input);
if(match.Success)
{
string output = match.Groups[0].Value;//"1.2.3"
//Or
string output = match.Value;//"1.2.3"
}
If the pound sign is the most relevant bit, rely on Split. Sample VB.NET code:
Dim inputString As String = " a.1.2.3 #4567 "
If (inputString.Contains("#")) Then
Dim firstBit As String = inputString.Split("#")(0).Trim()
Dim headingToRemove As String = "a."
Dim result As String = firstBit.Substring(headingToRemove.Length, firstBit.Length - headingToRemove.Length)
End If
As far as this is a multi-language question, here comes the translation to C#:
string inputString = " a.1.2.3 #4567 ";
if (inputString.Contains("#"))
{
string firstBit = inputString.Split('#')[0].Trim();
string headingToRemove = "a.";
string result = firstBit.Substring(headingToRemove.Length, firstBit.Length - headingToRemove.Length);
}
I guess another way using unrolled
\d+ (?: \. \d+ )+

How to capture exact td value in jquery independent of browser

I have li inside it i contain td.
var values = '';
$("#list4 li.add table .mytd").each(function () {
values = $(this).html() + '|' + values;
});
document.getElementById("MainContent_uscRetailParameters_hdRetailCustomerGroup").value = values;
__doPostBack('<%=txtRCCode.ClientID%>', '');
when I capture in hidden field it come like this
[alot of spaces]CHARMINSENSITIVE-1
with lot of spaces how can i retrieve the exact value in all browser. this space not found in Internet explorer. but in firefox it comes with spaces how could i capture the exact td value.
string lvValues = hdProductGroup.Value;
//string trim = lvValues.Replace(" ", "");
string trim = lvValues.Replace("\r", "");
trim = trim.Replace("\r", "");
trim = trim.Replace("\n", "");
trim = trim.Replace("\t", "");
string str = trim;
string[] list = str.Split('|');
You could trim it in Jquery? Try something like the following:
values = $.trim($(this).html() + '|' + values);
Or at the server using something like:
value = value.Trim();

C# replace part of string but only exact matches possible?

I have a string beginString = "apple|fruitsapple|turnip";
What I want to do is replace just apple with mango, not fruitsapple.
string fixedString = beginString.Replace("apple","mango"); This doesn't work because it replaces both apple and fruitsapple.
Any ideas?
beginString = "|" + beginString + "|";
fixedString = beginString.Replace("|apple|","|mango|");
This cannot be done in the way you have said since it will consider the entire string to be a string. You can do the split by | as you have used or else have the strings in a list and use equals and then replace it.
String[] words = beginString.Split("|");
now do the replace on words. works for any scenario.
The variation on other answers in LINQ style:
string fixedString = string.Join("|",
beginString
.Split('|')
.Select(s => s != "apple" ? s : "mango"));
Closest I can get. Was gonna suggest regular expression, but that won't always work as you want. You have to split the string first and then remake it.
string searchString = "apple";
string newString = "mango";
string beginString = "apple|fruitsapple|turnip";
string[] array = beginString.Split('|');
foreach (var item in array)
{
if (item == searchString)
item.Replace(searchString, newString);
}
string recreated = "";
new List<string>(array).ForEach(e => recreated += e + "|");
recreated.TrimEnd('|');
string newstr = Regex.Replace("apple|fruitsapple|turnip", #"\bapple\b", "mango");

Using LINQ to strip a suffix from a string if it contains a suffix in a list?

How can I strip a suffix from a string, and return it, using C#/LINQ? Example:
string[] suffixes = { "Plural", "Singular", "Something", "SomethingElse" };
string myString = "DeleteItemMessagePlural";
string stringWithoutSuffix = myString.???; // what do I do here?
// stringWithoutSuffix == "DeleteItemMessage"
var firstMatchingSuffix = suffixes.Where(myString.EndsWith).FirstOrDefault();
if (firstMatchingSuffix != null)
myString = myString.Substring(0, myString.LastIndexOf(firstMatchingSuffix));
You need to build a regular expression from the list:
var regex = new Regex("(" + String.Join("|", list.Select(Regex.Escape)) + ")$");
string stringWithoutSuffix = regex.Replace(myString, "");
// Assuming there is exactly one matching suffix (this will check that)
var suffixToStrip = suffixes.Single(x => myString.EndsWith(x));
// Replace the matching one:
var stringWithoutSuffix = Regex.Replace(myString, "(" +suffixToStrip + ")$", "");
OR, since you know the length of the matching suffix:
// Assuming there is exactly one matching suffix (this will check that)
int trim = suffixes.Single(x => myString.EndsWith(x)).Length;
// Remove the matching one:
var stringWithoutSuffix = myString.Substring(0, myString.Length - trim);

Categories

Resources