[英]Extracting character-number pairs from a string
以下列格式从串口连续接收字符-值对
h135v48s167
,其中 h 的值为 135,v 的值为 48,s 的值为 167(数值范围从 0 到 2000)。 我正在使用 if-else 语句根据h
、 v
和s
值执行特定操作。
我尝试使用正则表达式作为v(\d+)
来获取 v 的值,结果是v48
。
h
、 v
和s
的值。 单个正则表达式语句可以工作吗?以下是我使用它的代码部分 -
if (port.IsOpen) {
if (port.BytesToRead > 0) {
// port.WriteLine ("p");
string data = port.ReadExisting ();
if (!string.IsNullOrEmpty (data)) {
h = Regex.Match (data, @"h\d+").Value;
v = Regex.Match (data, @"v\d+").Value;
s = Regex.Match (data, @"s\d+").Value;
if (h > 150) {
// do something
}
if (v < 30) {
// do something
}
} else {
// default
}
}
}
使用正则表达式:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication11
{
class Program
{
const string FILENAME = @"c:\temp\test.txt";
static void Main(string[] args)
{
string input = "h135v48s167";
string pattern = "h(?'h'[^v]+)v(?'v'[^s]+)s(?'s'.*)";
Match match = Regex.Match(input,pattern);
string h = match.Groups["h"].Value;
string v = match.Groups["v"].Value;
string s = match.Groups["s"].Value;
}
使用正则表达式很好。 要允许任意字母,请使用[az]
(如果您只想捕获这些字母,请使用[hvs]
)。 您可以通过括号捕获字母和数字,并使用Match.Groups集合引用它们。
var data = "h135v48s167";
foreach (Match m in Regex.Matches(data, @"([a-z])(\d+)"))
{
var variable = m.Groups[1].Value[0];
var value = Convert.ToInt32(m.Groups[2].Value);
Console.WriteLine("{0}={1}", variable, value);
switch (variable)
{
case 'h':
// do something
break;
case 'v':
// do something
break;
case 's':
// do something
break;
}
}
给出:
h=135
v=48
s=167
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.