[英]Regex to extract string between characters satisfying a condition
我正在嘗試提取{
和}
之間的字符串,只要它們之間的字符串包含單詞ltrch
輸入字符串為:
{\\ 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}}}
我期望得到的輸出是:
{\\ltrch A }
, {\\b\\ltrch DD}
, {\\b\\i\\ul\\ltrch Italuic}
已嘗試使用\\{\\s*(((?!\\{|\\}).)+)\\s*ltrch.*\\}
和(?<=\\{)([^{]+)ltrch.*(?=\\})
,但是沒有獲得3場比賽。
我想,這樣的事情:
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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.