分割字符串以获取精确数据的简便方法

时间:2017-02-20 08:56:36

标签: c# string split

我需要从字符串得到x1 y1 x2 y2值;

string str = "Bbox(x1: 750; y1: 300; x2: 1100; y2: 600)";

从长远来看,我可以在括号之间获取字符串数据,例如;

int startIndex = rawStr.IndexOf("(") + "(".Length;
int stopIndex = rawStr.IndexOf(")");
string values = rawStr.Substring(startIndex, stopIndex - startIndex);

然后使用正则表达式,我将尝试逐个解析所有整数值。但是有没有简单的方法从字符串中抓取x1,y1,x2,y2?

5 个答案:

答案 0 :(得分:5)

您只能使用RegEx解决此问题

string str = "Bbox(x1: 750; y1: 300; x2: 1100; y2: 600)";
string pattern = @"(?<=[xy]\d: )\d+";
int[] result = System.Text.RegularExpressions.Regex.Matches(str,pattern) 
                                               .Cast<Match>()
                                               .Select(x => int.Parse(x.Value))
                                               .ToArray();

阐释:

  • (?<=)积极的背后,你的比赛必须从那开始,但它不是比赛的一部分
  • [yx]您的匹配必须以xy
  • 开头
  • \d:后跟一位数字:和一个空格
  • \d+您的匹配是一位数

如果你想保持参考,例如x1750您还可以将结果解析为Dictionary<string,int>()

string str = "Bbox(x1: 750; y1: 300; x2: 1100; y2: 600)";
string pattern = @"[yx]\d: \d+";
Dictionary<string, int> result = System.Text.RegularExpressions.Regex.Matches(str, pattern)
    .Cast<Match>().Select(x => x.Value.Split(new string[]{": "},  StringSplitOptions.None))
    .ToDictionary(x => x[0], x => int.Parse(x[1]));

答案 1 :(得分:4)

您可以运行以下正则表达式并将结果合并到字典中,这样您就可以轻松访问结果:

string str = "Bbox(x1: 750; y1: 300; x2: 1100; y2: 600)";

var regex = new Regex("(?<type>(x|y)\\d):\\s(?<val>\\d+)");

var result = regex.Matches(str).Cast<Match>()
    .ToDictionary(
        x => x.Groups["type"].Value, 
        x => int.Parse(x.Groups["val"].Value));

要获取所需的值,您可以使用以下代码:

var x1 = result["x1"];
var y1 = result["y1"];
var x2 = result["x2"];
var y2 = result["y2"];

正则表达式的命名组将提供某种可读性。

群组(?<type>(x|y)\\d):是一个名称为type的群组,用于搜索单个字符xyx|y),后跟单个数字({ {1}})

群组\\d:是一个名称为(?<val>\\d+)的群组,用于搜索一个或多个数字(val

答案 2 :(得分:4)

如果您不想使用正则表达式

string str = "Bbox(x1: 750; y1: 300; x2: 1100; y2: 600)";
var keyValuePairs = str.Split('(', ')')[1] // get what inside of the parentheses
                .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) // split them into {key:value}
                .Select(part => part.Split(':'))
                .ToDictionary(split => split[0].Trim(), split => int.Parse(split[1].Trim()));

如何获取x1:

var x1 = keyValuePairs["x1"];

答案 3 :(得分:0)

这可用于在不使用正则表达式或LINQ

的情况下解决您的问题
string str = "Bbox(x1: 750; y1: 300; x2: 1100; y2: 600)";
Dictionary<string, int> dict = new Dictionary<string, int>();
var values = str.Split(new char[2] { '(', ')'})[1].Split(new char[2] {':',';'});
for (int i = 0; i < values.Length; i+=2)
{
    dict.Add(values[i],int.Parse(values[i+1].Trim()));
}

答案 4 :(得分:0)

如果您在系统中有Bbox类,则可以将字符串转换为json格式并对其进行反序列化。

public static void Main(string[] args)
{
     string str = "Bbox(x1: 750; y1: 300; x2: 1100; y2: 600)".Replace("Bbox(", "{").Replace(")", "}").Replace(";", ",");

     Bbox box = JsonConvert.DeserializeObject<Bbox>(str);
}

class Bbox
{
     public int x1;
     public int y1;
     public int x2;
     public int y2;
 }