Reputation: 233
This is the string: "-random text- $0.15 USD"
What I want to extract is the "0.15" behind, excluding the $ and USD. So the text will only contain "0.15" with all other words gone.
How do I go about doing this?
Thanks in advance :)
Upvotes: 2
Views: 7430
Reputation: 116188
var result = Regex.Match("-random text- $0.15 USD", @"\$([ \d\.]+)USD")
.Groups[1].Value;
Upvotes: 2
Reputation: 111940
Using regexes
string str = "-random text- $0.15 USD";
Regex rx = new Regex(@"(?<=\$)[0-9]+\.[0-9]+(?= USD$)");
var res = rx.Match(str);
if (res.Success) {
var res2 = res.ToString();
}
The "main" part is [0-9]+\.[0-9]+
(one or more digits followed by a .
followed by one or more digits). This expression must follow a $
sign (?<=\$)
and must be followed by USD
(there is a space before USD
) plus end of string (?= USD$)
.
Online test: http://regexr.com?30aot
Upvotes: 4
Reputation: 449
Why use regexes when you can use the built-in String
methods?
int startIndex = myRandomString.LastIndexOf("$") + 1;
int lastIndex = myRandomString.LastIndexOf("U") - startIndex;
string price = random.Substring(startIndex, lastIndex);
Upvotes: 1
Reputation: 18260
Try this:
string sentence = "-random text- $0.15 USD";
string[] doubleArray = System.Text.RegularExpressions.Regex.Split(sentence, @"[^0-9\.]+")
.Where(c => c != "." && c.Trim() != "").ToArray();
if (doubleArray.Count() > 0)
{
double value = double.Parse(doubleArray[0]);
}
output:
.15
Upvotes: 1
Reputation: 6612
you can do something like this
string str = "-random text- $0.15 USD";
int startIndex = str.IndexOf("$")+1;
int length = str.IndexOf("USD", startIndex) - startIndex;
string output = str.Substring(startIndex, length).Trim();
Upvotes: 1
Reputation: 38810
Regular expressions are your friend here.
Use the RegEx
class (System.Text.RegularExpressions
), using a pattern of ([\d\.]+)
to extract the number + decimal place.
Upvotes: 1