2011-01-10 46 views
0
CriteriaCondition={FieldName=**{**EPS**}**$MinValue=(-201)$MaxValue=(304)$TradingPeriod=(-1)} 

幫助我獲得與第一字「= {」 &獲得下一以下字與結束「}」結束的第一個字。幫我用正則表達式分割字符串

的結果必然是:

Word1 = "CriteriaCondition" 
Word2 = "FieldName={EPS}$MinValue=(-201)$MaxValue=(304)$TradingPeriod=(-1)" 

而且帶有字符串 「字段名=(EPS)$ MINVALUE =( - 201)$的MaxValue =(304)$ TradingPeriod =( - 1)」,幫我分裂到對:

字段名EPS

MINVALUE -201

的MaxValue 304

TradingPeriod -1

謝謝。

+0

我不知道你可以用正則表達式乾淨地做到這一點。除非第二個匹配總是在字符串結尾附近結束。 – 2011-01-10 10:55:45

+0

第三次有`FieldName =(EPS)`。你期待多少嵌套?你會在你的值中使用`=`或`$`符號嗎?這是整個弦還是它是一個更大弦的一部分? – Kobi 2011-01-10 11:07:37

回答

1

這看起來像.NET captures的工作。與許多其他正則表達式相比,.NET記得重複捕獲組的所有捕獲,而不僅僅是最後一個捕獲組。我沒有在這裏安裝VS,所以我不能測試這個,但嘗試以下內容:

Match match = Regex.Match(subjectString, 
    @"(.*?)  # Match any number of characters and capture them 
    =\{   # Match ={ 
    (   # Match and capture the following group: 
    (?:  # One or more occurences of the following: 
     (?>[^$]+) # One or more characters except $, match possessively and capture 
     \$?  # Match the delimiting $ (optionally, because it's not there after the last item) 
    )+   # End of repeating group 
    )   # End of capturing group 
    \}   # Match } 
    ", 
    RegexOptions.IgnorePatternWhitespace); 
Console.WriteLine("Matched text: {0}", match.Value); 
Console.WriteLine("Word1 = \"{0}\"", match.Groups[1].Value); 
Console.WriteLine("Word2 = \"{0}\"", match.Groups[2].Value);  
captureCtr = 0; 
foreach (Capture capture in match.Groups[3].Captures) { 
    Console.WriteLine("  Capture {0}: {1}", 
          captureCtr, capture.Value); 
    captureCtr++; 
} 
1

爲第一分割的正則表達式是: ^([^ =] +)= {(。*)} $

它containts: - 線 的開始 - 任何字符的第一組不同的=(字1) - 字符= { - 所述串的剩餘(字2) - 字符} - 線的端

然後就可以字2分割成由字符$分離的部件,並施加類似的正則表達式(沒有{和})到每個部分

0

此正則表達式將讓你最有方式(讓你在使用named capture groups

@"(?<criteria>[^=]+)\=\{((?<params>[^$]+)(\$|}))+" 

然而得到的東西,保持你有興趣,我想了很多的字符串你不中的信息實際上並不關心,所以最好徹底擺脫它,然後從那裏解析字符串。

沿着這些線路

東西會約你要完成(如果你需要回去並進行更改)到底是什麼非常明確:

var temp = "CriteriaCondition={FieldName=**{**EPS**}**$MinValue=(-201)$MaxValue=(304)$TradingPeriod=(-1)}"; 

var startToken = "={"; 
var paramString = temp.Substring(temp.IndexOf(startToken) + startToken.Length); 
var cleanParamString = Regex.Replace(paramString, @"[*{}()]", ""); 

var parameters = cleanParamString.Split('$'); 

會給你用一個字符串數組以下行

FieldName=EPS 
MinValue=-201 
MaxValue=304 
TradingPeriod=-1 

並且您可以從那裏更容易地操作它們。