user1086902
user1086902

Reputation: 233

Extract specific text from a string

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

Answers (8)

L.B
L.B

Reputation: 116188

var result = Regex.Match("-random text- $0.15 USD",   @"\$([ \d\.]+)USD")
                  .Groups[1].Value;

Upvotes: 2

xanatos
xanatos

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

Brian Koser
Brian Koser

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

Niranjan Singh
Niranjan Singh

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

user5398447
user5398447

Reputation:

Have you thought about using regex?

Regex.Match("0.15");

Upvotes: 0

DotNetUser
DotNetUser

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

Moo-Juice
Moo-Juice

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

Matt Burland
Matt Burland

Reputation: 45155

Use a regex. Something like:

\d+\.*\d+

Upvotes: 1

Related Questions