[英]C# regex extracting tags
说我有一些像
Hi my name is <Name>
Hi <name>, shall we go for a <Drink>
是否可以通过c#正则表达式捕获标签? 如<Name>, <drink>
等? 我无法解决问题。
当然:
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>
"</?[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
}
为什么不做一些更简单的事情,例如使用C#的String.Replace? 您传入要替换的字符串,并为其提供要替换的任何值。
请参见此处的示例: http : //msdn.microsoft.com/zh-cn/library/fk49wtc1.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.