2010-03-27 99 views
0

說我有喜歡C#正則表達式提取標籤

Hi my name is <Name> 
Hi <name>, shall we go for a <Drink> 

幾個字符串是否有可能獲得通過的標籤C#正則表達式捕捉?像<Name>, <drink>等? 我無法弄清楚。

回答

2

肯定的:

Regex.Matches(myString, "<([^>]+)>"); 

PowerShell的例子:

PS> $s = @' 
>> Hi my name is <Name> 
>> Hi <name>, shall we go for a <Drink> 
>> '@ 
>> 
PS> [regex]::Matches($s, '<([^>]+)>') | ft 

Groups    Success Captures  Index  Length Value 
------    ------- --------  -----  ------ ----- 
{<Name>, Name}   True {<Name>}   14   6 <Name> 
{<name>, name}   True {<name>}   25   6 <name> 
{<Drink>, Drink}   True {<Drink>}  51   7 <Drink> 
+0

嗨,謝謝你的工作.....我一直在嘗試很多。*的中間。 – SysAdmin 2010-03-27 19:43:48

0

爲什麼不做更簡單的事情就像使用C#s String.Replace一樣?你傳入要替換的字符串,並給它任何你想要替換的值。

在這裏看到的例子:http://msdn.microsoft.com/en-us/library/fk49wtc1.aspx

+0

感謝您的回覆。 我不能這樣做你建議,因爲值在DB – SysAdmin 2010-03-27 19:37:53

1
"</?[a-z][a-z0-9]*[^<>]*>" 

要使用它,嘗試這樣的事情:

try 
{ 
    Regex regexObj = new Regex("</?[a-z][a-z0-9]*[^<>]*>", RegexOptions.IgnoreCase); 
    Match matchResults = regexObj.Match(subjectString); 
    while (matchResults.Success) 
    { 
     // Do Stuff 

     // matched text: matchResults.Value 
     // match start: matchResults.Index 
     // match length: matchResults.Length 
     matchResults = matchResults.NextMatch(); 
    } 
} 
catch (ArgumentException ex) 
{ 
    // Syntax error in the regular expression 
}