Extracting and reading decimal numbers from a string in C# - c#

I am relatively new to C# programming and I apologize if this is a simple matter, but I need help with something.
I need a function which will 'extract' regular AND decimal numbers from a string and place them in an array. I'm familiar with
string[] extractData = Regex.Split(someInput, #"\D+")
but that only takes out integers. If I have a string "19 something 58" it will take 19 and 58 and store them into two different array fields. However if I had "19.58 something" it will again take them as two separate numbers, while I want to register it as one decimal number.
Is there a way to make it 'read' such numbers as one decimal number, using Regex or some other method?
Thanks in advance.

Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication9
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
string[] inputs = {
"9 something 58" ,
"19.58 something"
};
foreach (string input in inputs)
{
MatchCollection matches = Regex.Matches(input, #"(?'number'\d*\.\d*)|(?'number'\d+[^\.])");
foreach (Match match in matches)
{
Console.WriteLine("Number : {0}", match.Groups["number"].Value);
}
}
Console.ReadLine();
}
}
}

Try this
Regex.Replace(someInput, "[^-?\d+\.]", ""))

Related

Replacing a string with an equal amount of underscores

I'm trying to replace all characters of a string with underscores. From my readings a string is ordinarily immutable which means it cannot be modified superficially once it has been created.
I've decided to use StringBuilder to carry out the modification, though I need the underscores to be for display purposes only (hangman game) and not actually alter the value.
I've read through the Microsoft docs and feel like I'm doing the right thing but cannot understand why it won't work. Code below.
using System;
using System.Text;
namespace randomtesting
{
internal class Program
{
static void Main(string[] args)
{
string str = "hello";
StringBuilder sb = new StringBuilder(str);
sb.Replace(str, "_", 0, str.Length);
Console.WriteLine(str);
}
}
}
Edit -
What I ended up doing to get it to do what I wanted - unsure if ideal. Please provide feedback if there's a better way to do it, feel like it's not the most efficient way, but it works.
using System;
using System.Text;
namespace randomtesting
{
internal class Program
{
static void Main(string[] args)
{
string str = "hello";
string strDisplayedAsUnderscores = new string('_', str.Length);
Console.WriteLine(strDisplayedAsUnderscores);
char guess = Convert.ToChar(Console.ReadLine().ToLower()); //reads the user's guess
int guessIndex = str.IndexOf(guess); //gets the index of the character guessed in relation to the original word
StringBuilder word = new StringBuilder(strDisplayedAsUnderscores); //converts the underscores into a StringBuilder string
if (str.Contains(guess))
{
Console.WriteLine(word.Replace('_', guess, guessIndex, 1));
//if guess is contained in the original word
//replace the indexed underscore with the
//guessed character
}
}
}
}
You want this System.String constructor
string result = new string('_', str.Length);

How to extract name and version from string

I have many filenames such as:
libgcc1-5.2.0-r0.70413e92.rbt.xar
python3-sqlite3-3.4.3-r1.0.f25d9e76.rbt.xar
u-boot-signed-pad.bin-v2015.10+gitAUTOINC+1b6aee73e6-r0.02df1c57.rbt.xar
I need to reliably extract the name, version and "rbt" or "norbt" from this. What is the best way? I am trying regex, something like:
(?<fileName>.*?)-(?<version>.+).(rbt|norbt).xar
Issue is the file name and version both can have multiple semi colons. So I am not sure if there is an answer by I have two questions:
What is the best strategy to extract values such as these?
How would I be able to figure out which version is greater?
Expected output is:
libgcc1, 5.2.0-r0.70413e92, rbt
python3-sqlite3, 3.4.3-r1.0.f25d9e76, rbt
u-boot-signed-pad.bin, v2015.10+gitAUTOINC+1b6aee73e6-r0.02df1c57, rbt
This will give you what you want without using Regex:
var fileNames = new List<string>(){
"libgcc1-5.2.0-r0.70413e92.rbt.xar",
"python3-sqlite3-3.4.3-r1.0.f25d9e76.rbt.xar",
"u-boot-signed-pad.bin-v2015.10+gitAUTOINC+1b6aee73e6-r0.02df1c57.rbt.xar"
};
foreach(var file in fileNames){
var spl = file.Split('-');
string name = string.Join("-",spl.Take(spl.Length-2));
string versionRbt = string.Join("-",spl.Skip(spl.Length-2));
string rbtNorbt = versionRbt.IndexOf("norbt") > 0 ? "norbt" : "rbt";
string version = versionRbt.Replace($".{rbtNorbt}.xar","");
Console.WriteLine($"name={name};version={version};rbt={rbtNorbt}");
}
Output:
name=libgcc1;version=5.2.0-r0.70413e92;rbt=rbt
name=python3-sqlite3;version=3.4.3-r1.0.f25d9e76;rbt=rbt
name=u-boot-signed-pad.bin;version=v2015.10+gitAUTOINC+1b6aee73e6-r0.02df1c57;rbt=rbt
Edit:
Or using Regex:
var m = Regex.Match(file,#"^(?<fileName>.*)-(?<version>.+-.+)\.(rbt|norbt)\.xar$");
string name = m.Groups["fileName"].Value;
string version = m.Groups["version"].Value;
string rbtNorbt = m.Groups[1].Value;
The output will be the same. Both approaches assum that "version" has one -.
Tested following code and work perfectly with Regex. I used option Right-To-Left
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication107
{
class Program
{
static void Main(string[] args)
{
string[] inputs = {
"libgcc1-5.2.0-r0.70413e92.rbt.xar",
"python3-sqlite3-3.4.3-r1.0.f25d9e76.rbt.xar",
"u-boot-signed-pad.bin-v2015.10+gitAUTOINC+1b6aee73e6-r0.02df1c57.rbt.xar"
};
string pattern = #"(?'prefix'.+)-(?'middle'[^-][\w+\.]+-[\w+\.]+)\.(?'extension'[^\.]+).\.xar";
foreach (string input in inputs)
{
Match match = Regex.Match(input, pattern, RegexOptions.RightToLeft);
Console.WriteLine("prefix : '{0}', middle : '{1}', extension : '{2}'",
match.Groups["prefix"].Value,
match.Groups["middle"].Value,
match.Groups["extension"].Value
);
}
Console.ReadLine();
}
}
}

Why is my £100,000 being converted to 100 and not 100000, possible issue with Regex?

I have the following code:
var totalDecimalList = Regex.Split(total, #"[^0-9\.]+").Where(c => c != "." && c.Trim() != "");
decimal totalDecimal = decimal.Parse(totalDecimalList.First());
Via my debug session
totalDecimal = 100 and not 100000
So the "," is obviously the cause of the issue and an incorrect regex in first line ie
#"[^0-9\.]+")
How can I correct this Regex please to account for the commas?
Thanks.
Better yet, let the built in parse function do the work for you:
using System;
using System.Globalization;
namespace StackOverflow_CurrencyParsing
{
class Program
{
static void Main(string[] args)
{
string total = "£100,000.00";
decimal totalDecimal = decimal.Parse(total, NumberStyles.Currency, CultureInfo.GetCultureInfo("en-gb"));
Console.WriteLine($"Total: {totalDecimal}");
Console.ReadKey();
}
}
}
Add the comma into the bracket expression of characters to match
e.g
[^0-9,\.]

regex pattern for the following string Amby : Dexter,Dexter : Karla

I have a input list that takes input in the above format and put them into a comma seperated string. I would like to get strings before and after colon(:).
I tried this regex pattern
string[] reg = Regex.Split(x, #"^(?:[\w ]\:\s[\w]+)+$");
but it doesnt seem to work. Please help.
Below is my code. This is a C# console application
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace test
{
class Program
{
static void Main(string[] args)
{
List<string> input = new List<string>();
Console.WriteLine("Please enter your input");
string readinput = Console.ReadLine();
input.Add(readinput);
while (readinput != "")
{
readinput = Console.ReadLine();
input.Add(readinput);
}
string x = string.Join(",", input.ToArray());
Console.WriteLine(x);
// using regex
string[] reg = Regex.Split(x, #"^(?:[\w ]\:\s[\w]+)+$");
Console.WriteLine(reg);
Console.ReadLine();
}
}
}
Sorry i was not very clear but the
input : Amby : Dexter,
Dexter : Karla,
Karla : Matt .....
Expected Output is Amby, Dexter, Karla, matt....
If I understood you correctly... User enters some strings, and then you join them with commas. After that you want to split that string by colons?
Why don't you use simpler solution like this:
string[] reg = x.Split(':').Select(s => s.Trim()).ToArray();
Maybe this will get you started:
new Regex(#"(([a-zA-Z])+(?:[\s\:\,]+))").Matches("...");
or this regex
"\b([a-zA-Z])+\b"
Iterate over the MatchCollection.

what is the purpose of Specific line in the Code

i am reading a book named "Visual C# 2012 Programming" and i came up with following code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ch05StringManupulationEx
{
class Program
{
static void Main(string[] args)
{
string myString = "String with small s";
char[] myChar = myString.ToCharArray();
foreach (char whatever in myString)
{
Console.WriteLine("{0}", whatever);
}
Console.Write("\nyou have entered {0} characters in String ",myString.Length);
Console.ReadKey();
}
}
}
i don't know what the aurthor is doing on line :
char[] myChar = myString.ToCharArray();
because he is not using the variable named myChar anywhere in the code and even though i commented the line and compiled the program the output is same, can any one explain what is the purpose of this line in this code ?
Probably they forgot to remove that line or show what does it do, It's an array of character, A string is full of characters, each letter of a string is a character, you can access any of these arrays by using a zero based numbers, for example:
string a = "Hello";
// Prints e
Console.WriteLine(a[2]);
You can change this line to myChar to understand, It's same to an array of string, Which means a string is an array of chars, here's the example:
foreach (char whatever in myChar)
{
Console.WriteLine("{0}", whatever);
}

Categories

Resources