2017-05-02 7 views
2

私はこのように見ている.TXTファイルを読み込むC#アプリケーションを持っているマージする:正規表現は、特定の単語を検索し、次の2行

  • リスト項目
  • リスト項目
  • アカウント
  • ファイブ
  • リスト項目
  • リスト項目
  • アカウント
  • リスト項目

は、私は特定の単語「アカウント」を見つけるために、正規表現を必要とし、その結果に

    を取得するには、以下の2行をマージ
  • アカウント番号5
  • アカウント番号6

私は最初の行を取得する次の正規表現がありますが、次の2行はどのようにマージできますか?

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

マルチライン正規表現( 'g'オプションとも呼ばれますが、C#APIに依存します)とマルチマッチを有効にするオプションが必要です。 正規表現については、この置換パターン 'Account \ 1 \ 2'を使って、' Account \ s *(?:([^ \ r \ n] *)\ r \ n){2} 。バックスラッシュを正しくエスケープして、_txt_ファイルからCRLFの '\ r \ n'行末を確認してください。 – Nikazo

+0

テキストファイル**は文字通り**そのように見えますか?ラインでの弾丸?代わりに引用セクションを行います。 – OmegaMan

答えて

0

1つの正規表現では可能かどうかわかりません。あなたは2つでそれを達成することができます。私ができるならば、マッチングのために一つ、別のスペース

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と同様のハードコーディングされた文字を使用しないでしょう。以下のサンプルは私のために働いた。

^\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. 

正規表現のオプション:

以下

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 
--------------- 

正規表現の説明のために出力されました0

MultiLine    -^and $ character will match beginning and end of any line and not just the start and end of the string 
関連する問題