This question already has answers here:
Finding all numbers in a string
(2 answers)
Closed 9 years ago.
I have a string like: "Hello I'm 43 years old, I need 2 burgers each for 1.99$".
I need to parse it and get all the numbers in it as double. So the function should return an array of values like: 43, 2, 1.99. In C++ I should've write all by myself, but C# has Regex and I think it may be helpful here:
String subjectString = "Hello I'm 43 years old, I need 2 burgers each for 1.99$";
resultString = Regex.Match(subjectString, #"\d+").Value;
double result = double.Parse(resultString);
After this, the resultString is "43" and result is 43.0. How to parse the string to get more numbers?
Your regex needs to be a little more complex to include decimals:
\d+(\.\d+)?
Then you need to get multiple matches:
MatchCollection mc = Regex.Matches(subjectString, "\\d+(\\.\\d+)?");
foreach (Match m in mc)
{
double d = double.Parse(m.Groups[0].Value);
}
Here is an example.
Try to use the following regular expression:
-?[0-9]+(\.[0-9]+)?
and then use Regex.Matches and iterate over the matches returned.
You should use Matches method to get a collection of matches. Also, you need to add dot to your regex
String subjectString = "Hello I'm 43 years old, I need 2 burgers each for 1.99$";
var matches = Regex.Matches(subjectString, #"\d+(\.\d+)?");
for (int i = 0; i < matches.Count; i++ )
{
double d = double.Parse(matches[i].Value);
}
Related
This question already has answers here:
How can I make part of regex optional?
(2 answers)
Closed 3 years ago.
I am trying to convert a string into a float.
I have a string that consists out of a number and some letters, I am using regex to remove the letters.
This is what I currenlty have:
string x = "0.5AA";
Console.WriteLine(float.Parse(Regex.Match(x.ToString(), #"(\d)+\.(\d+)").Value.Replace('.', ',')));
The output is: 0.5
This works if the string looks like 0.5AA, if the string is 100AA it crashes, is there a way to convert the 100AA to 100.0AA?
Try with this regex:
#"(\d)+(\.(\d)+)?"
It will optionally include the floating if they are there
Update 1
If you want to add the +- optionally change it to the following
[+-]?(\d)+(\.(\d)+)?
You can use Regex as below for select only numbers and not analphabets and then parse as float.
string x = "100AA";
string numString = Regex.Replace(x, "[^0-9.]", "");
Console.WriteLine(numString);
float y = float.Parse(numString);
Console.WriteLine(y);
This question already has answers here:
Regular Expression Groups in C#
(5 answers)
Closed 4 years ago.
string ABC = "This is test AZ12346";
Need value that occurs after AZ. AZ will always be present in the string and it will always be the last word. But number of characters after AZ will vary.
Output should be : AZ123456
Simply :
ABC.Substring(ABC.LastIndexOf("AZ"));
You can try LastIndexOf and Substring:
string ABC = "This is test AZ12346";
string delimiter = "AZ";
// "AZ123456"
string result = ABC.Substring(ABC.LastIndexOf(delimiter));
In case delimiter can be abscent
int p = ABC.LastIndexOf(delimiter);
string result = p >= 0
? ABC.Substring(p)
: result; // No delimiter found
If you are looking for whole word which starts from AZ (e.g. "AZ123", but not "123DCAZDE456" - AZ in the middle of the word) you can try regular expressions
var result = Regex
.Match(ABC, #"\bAZ[A-Za-z0-9]+\b", RegexOptions.RightToLeft)
.Value;
This question already has answers here:
Using regex to extract multiple numbers from strings
(4 answers)
Closed 5 years ago.
I have an input string like below:
"/myWS/api/Application/IsCarAvailable/123456/2017"
It is the end of a Web API call that I am making. I need to easily extract the 123456 from the URL.
I was hoping something like the below would work
string[] numbers = Regex.Split(input, #"\D+");
However, when I set a breakpoint on numbers and run the code it is showing an array of 3 elements?
Element at [0] is ""
Element at [1] is 123456
Element at [2] is 2017
Does anyone see why it would be getting the empty string as the first element?
I suggest matching, not splitting:
string source = #"/myWS/api/Application/IsCarAvailable/123456/2017";
string[] numbers = Regex
.Matches(source, "[0-9]+")
.OfType<Match>()
.Select(match => match.Value)
.ToArray();
Please, notice that \d+ in .Net means any unicode digits (e.g. Persian ones: ۰۱۲۳۴۵۶۷۸۹): that's why I put [0-9]+ pattern (RegexOptions.ECMAScript is an alternative if \d+ pattern is preferrable).
If your string is always in the same format, this would work:
string numbers = input.Split('/')[input.Split('/').Length - 2];
I think this is because the split method "splits" the string at the matching expression. So the empty string is the part before the first match.
Any reason why you would not use Regex.Matches(input,"\\d+") instead?
string numtest = "http://www.google.com/test/123456/7890";
var matchResult = Regex.Matches(numtest, "\\d+");
for (int i = 0; i < matchResult.Count; i++)
Console.WriteLine($"Element {i} is {matchResult[i].Value}");
Hope that helps. Regards!
This question already has answers here:
Find and extract a number from a string
(32 answers)
Closed 8 years ago.
I have some strings like "pan1", "pan2", and "pan20" etc. I need to extract number. I use it:
char ch = s[(s.Length) - 1];
int n = Convert.ToInt32(Char.GetNumericValue(ch));
But in case of, for example, "pan20" the result is not correct 0.
Index Approach
if you know where is the starting index of the number then simply you can do this :
string str = "pan20";
int number = Convert.ToInt32(str.Substring(3));
Note that "3" is the starting index of the number.
Fixed Prefix Approach
try to remove "pan" from the string; like this
string str = "pan20";
int number = Convert.ToInt32(str.Replace("pan", ""));
Regular Expression Approach
use regular expression only when string contains undetermined text inside
string str = "pan20";
int number = Convert.ToInt32(System.Text.RegularExpressions.Regex.Match(str, #"\d+").Value;
You can use for example regular expressions, for example [0-9]+$ to get the numbers in the end. See the Regex class in MSDN.
This question already has answers here:
Is this a bug in .NET's Regex.Split?
(2 answers)
Closed 9 years ago.
I have the following input:
void Main()
{
string inputData = "37.7879\r\n-122.3874\r\n40.7805\r\n-111.9288\r\n36.0667\r\n-115.0927\r\n37.7879\r\n-122.3874";
// string[] inputLines = Regex.Split(inputData, #"\r\n");
string[] inputLines = Regex.Split(inputData, #"(\r)?\n");
Console.WriteLine("The size of the list is: {0}", inputLines.Length);
bool results = inputLines.All(IsValidNumber);
foreach (string line in inputLines)
{
Console.WriteLine("{0} is: {1}", line, IsValidNumber(line));
}
}
// Define other methods and classes here
public bool IsValidNumber(string input)
{
Match match = Regex.Match(input, #"^-?\d+\.\d+$", RegexOptions.IgnoreCase);
return match.Success;
}
I am trying to a Regex.Split on #"\r\n", if I use the commented line, then I get the expected results. If I use the uncommented one, I do not get the results I expect. I'm almost 100% positive that my regex is correct if the "\r" doesn't exist (which may or may not be the case).
I'm expecting 8 values from inputData that I'm trying to validate if they're all valid numbers.
Is there a possibility that my "(\r)?" isn't working correctly? If so, what am I missing?
If your pattern contains a capturing group Regex.Split will capture the group as it's splitting the contents. This will give you 15 items instead of just 8.
If you're only trying to make a single character or character class optional, you don't need a group. Try getting rid of the group around \r:
string[] inputLines = Regex.Split(inputData, #"\r?\n");
Alternatively, yes, you can make it a non-capturing group:
string[] inputLines = Regex.Split(inputData, #"(?:\r)?\n");