2011-02-17 132 views
1

我有以下代码。请注意,通配符是我真正想要的。 (请在最终重构之前原谅糟糕的代码)。正则表达式返回

string findRegex = "{f:.*}"; 
Regex regex = new Regex(findRegex); 
foreach (Match match in regex.Matches(blockOfText)) 
{ 
    string findCapture = match.Captures[0].Value; 
    string between = findCapture.Replace("{f:", "").Replace("}", ""); 
} 

我不喜欢的代码是试图得到什么,我发现,双替换语句之间。有没有更好的办法?

其他:下面是一个简单的字符串

Dear {f:FirstName} {f:LastName}, 

回答

2

你可以用括号你匹配的组部分和以后提取它:如果你想要的是两场比赛

string findRegex = "{f:(.*?)}"; 
Regex regex = new Regex(findRegex); 
foreach (Match match in regex.Matches(blockOfText)) { 
    string between = match.Captures[1].Value; 
} 

(如为你的名字的最后一个例子),使两组:

string findRegex = "{f:(.*?)}.*?{f:(.*?)}"; 
Regex regex = new Regex(findRegex); 
foreach (Match match in regex.Matches(blockOfText)) { 
    string firstName = match.Captures[1].Value; 
    string lastName = match.Captures[2].Value; 
} 
+0

看来正则表达式捕获“名字”{f:姓氏“作为一个捕获。我在我的文章中添加了示例。 – 2011-02-17 23:07:24

+1

@Valamas:啊,那么你需要一个非贪婪的匹配:`。*?`。我正在更新我的信息。 – Tim 2011-02-17 23:14:29

1

使用群组:

string findRegex = "{f:(.*)}"; 
Regex regex = new Regex(findRegex); 
foreach (Match match in regex.Matches(blockOfText)) 
{ 
    string findCapture = match.Groups[1].Value; 
    // ... rest 
}