<分区>
我需要一些帮助来编写正则表达式语句来拆分包含一些标签的字符串(不是真正的 HTML,我只是使用 <i>
和 <b>
标签来格式化一些文本),并保留分隔符。例如这个字符串:
<b>a bold quote:</b> this is some sample test. How <i>do</i> I do this?
将转换为:
<b>a bold quote:</b>
this is sample text. How
<i>do</i>
I do this?
<分区>
我需要一些帮助来编写正则表达式语句来拆分包含一些标签的字符串(不是真正的 HTML,我只是使用 <i>
和 <b>
标签来格式化一些文本),并保留分隔符。例如这个字符串:
<b>a bold quote:</b> this is some sample test. How <i>do</i> I do this?
将转换为:
<b>a bold quote:</b>
this is sample text. How
<i>do</i>
I do this?
最佳答案
对于大多数正则表达式风格,您可以通过将拆分表达式放在捕获组中来做一些接近的事情。
new Regex("(<[^>]+>)").Split("test <b>string</b>")
生成包含项目的数组
test
<b>
string
</b>
(最后是一个空字符串)
如果你想找到标签里面的东西,而且它们绝对没有以任何方式嵌套,你可以这样做
new Regex("(<[^>]+>[^<]*</[^>]+>)").Split("test <b>string</b>")
=
test
<b>string</b>
关于c# - 用标签拆分字符串,保留定界符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21567294/