2017-02-20 46 views
0

我需要從字符串得到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?

+0

x1,y1,x2,y2 *總是*按順序出現嗎? –

+0

@AndrewMorton是的 – goGud

回答

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其搜索隨後單個數字(\\d

(?<val>\\d+)組單個字符xyx|y)的基團:與名稱val其搜索一個的基團或多個數字(\\d+

5

你可以用正則表達式解決這個問題只有

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+你的比賽時間是執法機關個位數

如果你想保留例如之間的參考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])); 
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"]; 
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())); 
} 
0

如果在系統B-盒類,您可以將字符串轉換爲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; 
} 
相關問題