用标签拆分字符串,保留分隔符

Jas*_*son 1 c# regex

我需要一些帮助编写正则表达式语句来拆分包含一些标签的字符串(不是真正的HTML,我只是使用使用<i><b>标签格式化一些文本),并保留分隔符.例如这个字符串:

<b>a bold quote:</b> this is some sample test. How <i>do</i> I do this?
Run Code Online (Sandbox Code Playgroud)

将转变为:

<b>a bold quote:</b>
 this is sample text. How 
<i>do</i>
 I do this?
Run Code Online (Sandbox Code Playgroud)

Ste*_*ard 5

对于大多数正则表达式,您可以通过将拆分表达式放在捕获组中来做一些事情.

new Regex("(<[^>]+>)").Split("test <b>string</b>")
Run Code Online (Sandbox Code Playgroud)

生成一个包含项目的数组

test  
<b> 
string 
</b> 
Run Code Online (Sandbox Code Playgroud)

(最后是一个空字符串)

如果你想找到标签内的东西,并且它们肯定没有以任何方式嵌套,你可以做到

new Regex("(<[^>]+>[^<]*</[^>]+>)").Split("test <b>string</b>")
Run Code Online (Sandbox Code Playgroud)

=

test  
<b>string</b> 
Run Code Online (Sandbox Code Playgroud)