c# – 正则表达式捕获标记和未标记的内容
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 正则表达式捕获标记和未标记的内容,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1600字,纯文字阅读大概需要3分钟。
内容图文
![c# – 正则表达式捕获标记和未标记的内容](/upload/InfoBanner/zyjiaocheng/796/29ccb05d3bfa4114b156f81bb2df8704.jpg)
我想要做的是从字符串中解析一些自定义标签,同时也获取未标记的内容.例如,我有以下字符串
Hello World <Red>This is some red text </Red> This is normal <Blue>This is blue text </Blue>
我有一个工作正则表达式来获取标记的内容使用
<(?<tag>\w*)>(?<text>.*)</\k<tag>>
但是,这会回来
tag: Red
text: This is some red text
tag: Blue
text this is blue text
我需要的是获得未标记内容的匹配,所以我会得到4个匹配,两个像上面一样,还有“Hello World”和“This is normal”.
这是正则表达式可能的东西吗?
举个例子,这是我目前的功能:
public static List<FormattedConsole> FormatColour(string input)
{
List<FormattedConsole> formatted = new List<FormattedConsole>();
Regex regex = new Regex("<(?<Tag>\\w+)>(?<Text>.*?)</\\1>", RegexOptions.IgnoreCase
| RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
MatchCollection ms = regex.Matches(input);
foreach (Match match in ms)
{
GroupCollection groups = match.Groups;
FormattedConsole format = new FormattedConsole(groups["Text"].Value, groups["Tag"].Value);
formatted.Add(format);
}
return formatted;
}
如上所述,这只返回标签之间的匹配.我还需要没有标签的文本.
(顺便说一下FormattedConsole只是一个包含文本和颜色的容器)
解决方法:
你可以试试这个:
string sentence = "Hello World <Red>This is some red text </Red> This is normal <Blue>This is blue text </Blue>";
string[] matchSegments = Regex.Split(sentence,@"(<\w+>)(.*?)<\/\w+>");
foreach (string value in matchSegments)
{
if(value.Contains("<") && value.Contains(">"))
Console.Write(value);
else
Console.WriteLine(value);
}
输出:
Hello World
<Red>This is some red text
This is normal
<Blue>This is blue text
内容总结
以上是互联网集市为您收集整理的c# – 正则表达式捕获标记和未标记的内容全部内容,希望文章能够帮你解决c# – 正则表达式捕获标记和未标记的内容所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。