2017-05-02 20 views
2

我有,我讀一個.txt文件看起來像這樣一個C#應用程序:正則表達式查找特定的單詞和合並下面兩行

  • 列表項
  • 列表項
  • 帳戶
  • 列表項
  • 列表項
  • 帳戶
  • 列表項

我需要一個正則表達式來查找特定單詞「帳戶」,然後合併下面兩行得到的結果

  • 賬號五
  • 賬號六

我有以下正則表達式,我得到的第一行,但我怎麼能合併以下兩行?

[\n\r].*Account\s*([^\n]*) 
+0

您應該有一個選項來啓用多行正則表達式(稱爲'g'選項,但取決於C#API)和多重匹配。 關於你的正則表達式,你應該更喜歡'Account \ s *(?:([^ \ r \ n] *)\ r \ n){2}'這個替換模式'Account \ 1 \ 2' 。確保正確地反斜線並從_.txt_文件中獲得CRLF'\ r \ n'結尾行。 – Nikazo

+0

文本文件**的字面**看起來像那樣嗎?有一條子彈?做一個報價部分。 – OmegaMan

回答

0

不確定,如果一個正則表達式有可能。你可以用兩個來實現。一個匹配,另一個是用來與空間

var regex = new Regex(@"Account\r\n\w*\r\n\w*"); 
var regex_newline = new Regex("(\r\n|\r|\n)"); 
var matches = regex.Matches(input); 
foreach(var match in matches) 
{ 
    Console.WriteLine(regex_newline.Replace(match.ToString(), " ")); 
}; 
0

更換新行我想,如果我能避免使用\r\n和類似的硬編碼的字符。下面的示例爲我工作。

static void Main() { 
     var str = @"List item 1 
List item 2 
Account 
Number 
Five 
List item 3 
List item 4 
Account 
Number 
Six 
List item 5"; 

     var newStr = Regex.Replace(str, @"^\s*(Account)\s*^\s*(.*?)\s*$\s*^\s*(.*?)\s*$", "$1 $2 $3", RegexOptions.Multiline | RegexOptions.Singleline); 
     Console.WriteLine($"Original: \r\n{str}\r\n---------------\r\n"); 
     Console.WriteLine($"New: \r\n{newStr}\r\n---------------\r\n"); 
    } 

下面是它

Original: 
List item 1 
List item 2 
Account 
Number 
Five 
List item 3 
List item 4 
Account 
Number 
Six 
List item 5 
--------------- 

New: 
List item 1 
List item 2 
Account Number Five 
List item 3 
List item 4 
Account Number Six 
List item 5 
--------------- 

正則表達式解釋輸出:

^\s*(Account)\s*  - Match from start of line followed by Account. If there are white spaces around account, then eat them up too. 
^\s*(.*?)\s*$\s*  - Match from start of line, followed by optional white-spaces, followed by capturing all text on that line, followed by optional white-spaces, and then end-of-line. The last \s* eats up the end-of-line character(s) 
^\s*(.*?)\s*$   - Same as above explanation, except that we don't want to eat up the end-of-line character(s) at the end 

更換:

"$1 $2 $3"    - the 3 items we captured in the above regex with a space in between them. 

正則表達式選項:

MultiLine    -^and $ character will match beginning and end of any line and not just the start and end of the string 
相關問題