从句子中提取并添加数字 [英] extract and add number from a sentence

查看:65
本文介绍了从句子中提取并添加数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,先生,

我正在编写一个应用程序.应用程序中的一种方法需要

1.从字符串中提取所有数字值.和
2.对所有提取的值求和,例如,

string somedata =我要1个可乐,1个大拇指等.";


谢谢everrne.

Hello Sir,

i am writing an application. One of the method in the application needs to

1. extract all number values from a string. and
2. Sum all the extracted values for example,

string somedata="I want 1 coke, 1 Thumbs up etc.";


Thank you everrne.

推荐答案

VJ的解决方案非常好.该解决方案的另一个版本可能对您有所帮助,

VJ''s solution is pretty good. Another version of the solution might be helpful to you,

namespace ConsoleApplication24
{
    using System;
    using System.Linq;
    using System.Text.RegularExpressions;

    class Program
    {
        static void Main(string[] args)
        {
            string sentence = "I want 1 coke, 1 Thumbs up etc.";
            string[] numbers = Regex.Split(sentence, @"\D+");
            int parsedValue = default(int);
            int result = numbers
                .SkipWhile(item => string.IsNullOrEmpty(item))
                .Sum(item => Int32.TryParse(item, out parsedValue) ? parsedValue : parsedValue);
            Console.WriteLine("Result {0}", result);
        }
    }
}




希望对您有所帮助:)




Hope it helps :)


LINQ Regex 可以按以下方式使用.
LINQ and Regex can be used as follows.
string sentence = @"I want 1 coke, 1 Thumbs up etc.";
int sum = sentence
    .Split(new char[]{' ','\t','\n','\r'}, StringSplitOptions.RemoveEmptyEntries)
    .Where (s => Regex.IsMatch(s,@"\d+", RegexOptions.CultureInvariant))
    .Sum (s => int.Parse(s));
Console.WriteLine (sum);



如果要处理十进制数字,则应相应地修改Regex 模式和Parse.

替代

作为替代方法,可以使用Regex.Matches方法仅提取数字并将其求和,如下所示:



If you want to handle decimal numbers then the Regex pattern and Parse are to be modified accordingly.

Alternative

As an alternative Regex.Matches method can be used to extract only the numbers and sum them up as shown below:

string inputText = @"I want 1 coke, 1 Thumbs up etc. . 2. 2.0 .5 5.5 ";
var sum = Regex.Matches(inputText,@"(?:\d*\.\d+|\d+\.\d*|\d+)",
    RegexOptions.CultureInvariant).OfType<Match>().Sum (m => double.Parse(m.Value));
Console.WriteLine (sum);

//Output
//12


这篇关于从句子中提取并添加数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆