【问题标题】:extract number out strings c# [closed]提取数字字符串c#[关闭]
【发布时间】:2017-05-11 15:12:19
【问题描述】:

我有字符串:

  1. 湿度:33 %
  2. 温度:25.7摄氏度
  3. 可见光:112 lx
  4. 红外辐射:1802.5 mW/m2
  5. 紫外线指数:0.12
  6. CO2:404 ppm CO2
  7. 压力:102126帕

我必须提取 'Humidity:' 之后的所有数字,.. 我正在考虑使用 Regex 类,但我不知道该怎么做

我获取串行数据的代码:

namespace Demo1Arduino

{

public partial class MainWindow : Window
{
    private SerialPort port;
    DispatcherTimer timer = new DispatcherTimer();
    private string buff; 

    public MainWindow()
    {
        InitializeComponent();
    }

    private void btnOpenPort_Click(object sender, RoutedEventArgs e)
    {
        timer.Tick += timer_Tick;          
        timer.Interval = new TimeSpan(0, 0, 0, 0, 500);           
        timer.Start();

        try
        {
            port = new SerialPort();                     // Create a new SerialPort object with default settings.
            port.PortName="COM4";
            port.BaudRate = 115200;                        //  Opent de seriele poort, zet data snelheid op 9600 bps.
            port.StopBits = StopBits.One;                // One Stop bit is used. Stop bits separate each unit of data on an asynchronous serial connection. They are also sent continuously when no data is available for transmission.
            port.Parity = Parity.None;                   // No parity check occurs. 
            port.DataReceived += Port_DataReceived;                                                                                   
            port.Open();                                 // Opens a new serial port connection.
            buff = ""; 
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message); 
        }
    }
    private void timer_Tick(object sender, EventArgs e)
    {
       try
        {
            if(buff != "") 
            {
                textBox.Text += buff;
                buff = ""; 
            }
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message); 
        }
    }

    private void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        byte[] buffer = new byte[128];
        int len = port.Read(buffer, 0, buffer.Length); // .Read --> Reads a number of characters from the SerialPort input buffer and writes them into an array of characters at a given offset.

        if(len>0)
        {
            string str = ""; 
            for (int i=0; i<len; i++)
            {
                if (buffer[i] != 0)
                {
                    str = str + ((char)buffer[i]).ToString();
                }
            }
            buff += str; 
        } 
       // throw new NotImplementedException();
    }
}

谢谢

【问题讨论】:

  • 你为什么要为此使用正则表达式? String.Split(':');dotnetfiddle.net/OpX8Nq 。此外,您提供的任何代码都与您正在尝试做的事情无关......
  • 您的问题基本上是 - “我如何从字符串中获取数字”?您的其余代码无关紧要。我没有看到足够的研究来解决这个问题。所以不是“我想要这个。我该怎么做?”服务。您需要提供您可能遇到的问题的详细信息以及您尝试解决的问题。我建议您以stackoverflow.com/questions/4734116/… 为起点...
  • 你的问题是什么?我所看到的只是“这是任务”和“这是我的代码”。在这里,我们提出了一些具体的问题,即我们提供了一些代码和所需的输出以及我们得到的而不是这个。

标签: c# regex serial-port substring extract


【解决方案1】:

尝试正则表达式,唯一的技巧是 CO2m2 - 我们不想要 2 这就是我添加的原因\b:

  string source =
    @"Humidity: 33 %
      Temperature: 25.7 deg C
      Visible light: 112 lx
      Infrared radiation: 1802.5 mW/m2
      UV index: 0.12
      CO2: 404 ppm CO2
      Pressure: 102126 Pa";

  string[] numbers = Regex
      .Matches(source, @"\b[0-9]+(?:\.[0-9]+)?\b")
      .OfType<Match>()
      .Select(match => match.Value)
      .ToArray();

测试

   Console.Write(string.Join("; ", numbers));

结果

   33; 25.7; 112; 1802.5; 0.12; 404; 102126

【讨论】:

  • 你为什么选择[0-9]+而不是\d+
  • @ThePerplexedOne: \d 在 C# 中包含 所有 位,例如波斯人۰ ۱ ۲ ۳ ۴ ۵ ۶ ۷ ۸ ۹
  • @ThePerplexedOne:简单测试:if (Regex.IsMatch("۰۱۲۳", @"\d+")) Console.Write("matched!"); 如果您更喜欢\d,您必须添加选项.Matches(source, @"\b\d+(?:\.\d+)?\b", RegexOptions.ECMAScript) 请注意RegexOptions.ECMAScript
  • 我明白了。谢谢你:)
【解决方案2】:

在不知道类型的情况下获取多个数字是没有意义的。我将值放入字典中,以便稍后在代码中使用该数字。请参阅下面的代码和https://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication55
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] inputs = {
                "Humidity: 33 %",
                "Temperature: 25.7 deg C",
                "Visible light: 112 lx",
                "Infrared radiation: 1802.5 mW/m2",
                "UV index: 0.12",
                "CO2: 404 ppm CO2",
                "Pressure: 102126 Pa"
                             };

            string pattern = @"^(?'name'[^:]+):\s(?'value'[\d.]+)";

            Dictionary<string, decimal> dict = new Dictionary<string,decimal>();
            foreach(string input in inputs)
            {
                Match match = Regex.Match(input,pattern);
                string name = match.Groups["name"].Value;
                decimal value = decimal.Parse(match.Groups["value"].Value);

                Console.WriteLine("name = '{0}', value = '{1}'", name, value);
                dict.Add(name, value);
            }
            Console.ReadLine();
        }
    }

}

【讨论】:

  • 从技术上讲,在不知道类型的情况下获取多个数字是否有意义取决于格式:如果我们保证第一个值是湿度,第二个是温度等。我们可以不用名字。但是,在一般情况下,名称是必需的。 +1。进一步泛化增加了 domain - deg C, %, Pa etc.
  • 我不会雇用任何有这种想法的人。
猜你喜欢
  • 2015-10-04
  • 1970-01-01
  • 1970-01-01
  • 2012-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-13
相关资源
最近更新 更多