简体   繁体   English

从字符串中提取特定文本

[英]Extract specific text from a string

This is the string: "-random text- $0.15 USD" 这是字符串:“ - random text- $ 0.15 USD”

What I want to extract is the "0.15" behind, excluding the $ and USD. 我要提取的是“0.15”,不包括美元和美元。 So the text will only contain "0.15" with all other words gone. 所以文本只包含“0.15”,其他所有单词都消失了。

How do I go about doing this? 我该怎么做呢?

Thanks in advance :) 提前致谢 :)

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). “主要”部分是[0-9]+\\.[0-9]+ (一个或多个数字后跟a .后跟一个或多个数字)。 This expression must follow a $ sign (?<=\\$) and must be followed by USD (there is a space before USD ) plus end of string (?= USD$) . 此表达式必须遵循$符号(?<=\\$)并且必须后跟USDUSD之前有空格)加上字符串结尾(?= USD$)

Online test: http://regexr.com?30aot 在线测试: http//regexr.com?30aot

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

Use a regex. 使用正则表达式。 Something like: 就像是:

\d+\.*\d+

Regular expressions are your friend here. 正则表达式是你的朋友。

Use the RegEx class ( System.Text.RegularExpressions ), using a pattern of ([\\d\\.]+) to extract the number + decimal place. 使用RegEx类( System.Text.RegularExpressions ),使用([\\d\\.]+)提取数字+小数位。

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();

Why use regexes when you can use the built-in String methods? 为什么在使用内置String方法时使用正则表达式?

 int startIndex = myRandomString.LastIndexOf("$") + 1;
 int lastIndex = myRandomString.LastIndexOf("U") - startIndex;

 string price = random.Substring(startIndex, lastIndex);

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

你有没有想过使用正则表达式

Regex.Match("0.15");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM