2012-01-08 107 views
0

我想基於使用正則表達式的開始和結束字符來創建一個字符串數組。如何查找由某個開始和結束字符分隔的字符串

一個例子將幫助我解釋。 考慮'$'作爲我的起始標識符和'|'作爲我從下面的字符串結束標識符

stack $ over |流程$ stack |交換

正則表達式應該找到在上面的字符串超過堆棧

[編輯,包括在OP的評論代碼片段...]

string testingString = "stack $over| flow $stack| exchange"; 
var pattern = @"(?$.*?|)"; // also tried @"\$[^|]\|" 
foreach (var m in System.Text.RegularExpressions.Regex.Split(testingString, pattern)) {  
    Response.Write(m); 
} 
// output == stack $over| flow $stack| exchange 
+0

那你應該......那樣做。或者至少*嘗試*做到這一點。 [你試過了什麼?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) – 2012-01-08 07:02:41

+0

「什麼阻止你?」 – Shai 2012-01-08 07:04:03

+0

(?$。*?|)試過類似這樣的東西,但我對正則表達式知之甚少 – Shah 2012-01-08 07:05:30

回答

2

我會使用後視和前瞻來排除匹配的開始和結束分隔符。

string testingString = @"stack $over| flow $stack| exchange"; 

MatchCollection result = Regex.Matches 
    (testingString, 
      @"  
       (?<=\$) # This is a lookbehind, it ensure there is a $ before the string 
       [^|]* # Match any character that is not a | 
       (?=\|) # This is a lookahead,it ensures that a | is ahead the pattern 
      " 
      , RegexOptions.IgnorePatternWhitespace); 

foreach (Match item in result) { 
    Console.WriteLine(item.ToString()); 
} 

RegexOptions.IgnorePatternWhitespace是能夠寫出易讀的正則表達式,還可以使用在正則表達式評論一個有用的選項。

+0

+1這是一個很好的答案,完全可重用! – 2014-06-05 14:42:37

1

在正則表達式$是一個特殊字符,意思是「匹配字符串的結尾」。 對於字面$您需要轉義它,請嘗試\$

同理|是正則表達式中的一個特殊字符,需要轉義。

嘗試\$.*?\|\$[^|]+\|

瞭解網絡中的正則表達式,例如here

[更新] 在回答您的意見,要提取文本由$|界定,它不分裂。嘗試Regex.Matches而不是Regex.Split

Regex t = new Regex(@"\$([^|]+)\|"); 
MatchCollection allMatches = t.Matches("stack $over| flow $stack| exchange"); 
+0

我試過但沒有工作。我可以改變我的結尾字符'|'。如果這是問題的原因 – Shah 2012-01-08 07:22:44

+0

爲什麼你不給你的輸入字符串,你使用的確切代碼和結果。這會幫助我們極大地幫助你。 – 2012-01-08 07:24:44

+0

@ mathematical.coffee在補充完字符類後忘了'+',否則你的答案有效 – fge 2012-01-08 11:36:00

相關問題