正则表达式

时间:2010-12-16 06:55:27

标签: c# regex

如何使用正则表达式

从以下字符串中获取数值
   AD  .6547 BNM

结果应为

 .6547

请帮我这样做

提前致谢

4 个答案:

答案 0 :(得分:3)

var src = "AD  .6547 BNM";

var match = Regex.Match(input, @"(\.\d+)");
if (match.Success) {
    var result = match.Groups[1].Value;
}

答案 1 :(得分:3)

我通常会在Regex.Match中开始使用。如果要解析多个字符串,通过实例化Regex对象并使用Matches实例方法而不是使用静态Match方法,您将获得一些好处。这只是一个小小的好处,但是嘿......

如果您有严重的性能问题且输入字符串的格式是静态的,您甚至可以考虑放弃正则表达式而不是string.Substring甚至是string.Split。您的问题促使我测量了几种不同方法之间的性能差异,代码如下。

static void TestParse()
    {
        List<string> strList = new List<string>
        {
            "AD  .1234 BNM", 
            "AD  .6547 BNM", 
            "AD  .6557 BNM", 
            "AD  .6567 BNM", 
            "AD  .6577 BNM", 
            "AD  .6587 BNM", 
            "AD  .6597 BNM", 
            "AD  .6540 BNM", 
            "AD  .6541 BNM", 
            "AD  .6542 BNM"
        };

        Stopwatch stopwatch = new Stopwatch();
        string result = "";
        stopwatch.Start();
        for (int i=0; i<100000; i++)
            foreach (string str in strList)
            {
                var match = Regex.Match(str, @"(\.\d+)");
                if (match.Success)
                    result = match.Groups[1].Value;
            }
        stopwatch.Stop();
        Console.WriteLine("\nTotal Regex.Match time 1000000 parses: {0}", stopwatch.ElapsedMilliseconds);

        result = "";
        stopwatch.Reset();
        stopwatch.Start();
        Regex exp = new Regex(@"(\.\d+)", RegexOptions.IgnoreCase);
        for (int i = 0; i < 100000; i++)
            foreach (string str in strList)
                result = exp.Matches(str)[0].Value;
        stopwatch.Stop();
        Console.WriteLine("Total Regex object time 1000000 parses: {0}", stopwatch.ElapsedMilliseconds);

        result = "";
        stopwatch.Reset();
        stopwatch.Start();
        for (int i = 0; i < 100000; i++)
            foreach (string str in strList)
                result = str.Substring(4, 5);
        stopwatch.Stop();
        Console.WriteLine("Total string.Substring time 1000000 parses: {0}", stopwatch.ElapsedMilliseconds);

        result = "";
        stopwatch.Reset();
        stopwatch.Start();
        char[] seps = { ' ' };
        for (int i = 0; i < 100000; i++)
            foreach (string str in strList)
                result = str.Split(seps, StringSplitOptions.RemoveEmptyEntries)[1];
        stopwatch.Stop();
        Console.WriteLine("Total string.Split time 1000000 parses: {0}", stopwatch.ElapsedMilliseconds);
    }

答案 2 :(得分:2)

\.\d+

应该做一些c#代码:

Regex exp = new Regex(
    @"(\.\d+)",
    RegexOptions.IgnoreCase);

string InputText = "AD .1234";
MatchCollection MatchList = exp.Matches(InputText);
Match FirstMatch = MatchList[0];
string value = MatchList[0].value;

答案 3 :(得分:1)

尝试

\.\d*

它会选择“。”和之后的所有数字。