正则表达式在满足条件的字符之间提取字符串

时间:2016-03-17 06:56:56

标签: c# .net regex pattern-matching

我正在尝试在{}之间提取字符串,前提是其中的字符串包含单词ltrch

输入字符串是:

  

{\ RTF1 \ ANSI \ ansicpg1252 \ UC1 \ htmautsp \ deff2 {\ fonttbl {\ F0 \ fcharset0   Times New Roman;} {\ f2 \ fcharset0 Segoe   UI;}} {\ colortbl \ red0 \ green0 \ blue0; \ red255 \ green255 \ blue255;} \湖\ HICH \ DBCH \ PARD \平原\ ltrpar \ itap0 {\ lang1033 \ FS18 \ F2 \ CF0   \ cf0 \ ql {\ f2 {\ ltrch A} {\ b \ ltrch DD} \ li0 \ ri0 \ sa0 \ sb0 \ fi0 \ ql \ par} {\ f2   {\ b \ i \ ul \ ltrch Italuic} \ li0 \ ri0 \ sa0 \ sb0 \ fi0 \ ql \ par}}}

我期望获得的输出是:

{\ltrch A }{\b\ltrch DD}{\b\i\ul\ltrch Italuic}

一直在努力 \{\s*(((?!\{|\}).)+)\s*ltrch.*\}(?<=\{)([^{]+)ltrch.*(?=\}),但是没有得到3场比赛。

1 个答案:

答案 0 :(得分:0)

我想,就像这样:

String source = @"{\rtf1\ansi\ansicpg1252\uc1\htmautsp\deff2{\fonttbl{\f0\fcharset0 Times New Roman;}{\f2\fcharset0 Segoe UI;}}{\colortbl\red0\green0\blue0;\red255\green255\blue255;}\loch\hich\dbch\pard\plain\ltrpar\itap0{\lang1033\fs18\f2\cf0 \cf0\ql{\f2 {\ltrch A }{\b\ltrch DD}\li0\ri0\sa0\sb0\fi0\ql\par}
{\f2 {\b\i\ul\ltrch Italuic}\li0\ri0\sa0\sb0\fi0\ql\par}
    }
  }";

// start with {
// followed by any number of any characters with { and } excluded
// ltrch 
// followed by any number of any characters with { and } excluded
// end with }
String pattern = @"\{[^{}]*ltrch[^{}]*\}";

var result = Regex.Matches(source, pattern)
  .OfType<Match>()
  .Select(match => match.Value);

 // Test:    
 // {\ltrch A }, {\b\ltrch DD}, {\b\i\ul\ltrch Italuic}
 Console.Write(String.Join(", ", result));