1

I need some helping writing a regex statement to split a string containing some tags (not true HTML, I'm just using using <i> and <b> tags to format some text), and keep the delimiters. For example this string:

<b>a bold quote:</b> this is some sample test. How <i>do</i> I do this?

Would be transformed to:

<b>a bold quote:</b>
 this is sample text. How 
<i>do</i>
 I do this?
1

1 Answer 1

5

With most regex flavors, you do something close by putting the splitting expression in a capture group.

new Regex("(<[^>]+>)").Split("test <b>string</b>")

produces an array with the items

test  
<b> 
string 
</b> 

(and an empty string at the end)

If you want to find the things inside the tags, and they're definitely not nested in any way, you can do

new Regex("(<[^>]+>[^<]*</[^>]+>)").Split("test <b>string</b>")

=

test  
<b>string</b> 
3
  • I'm looking to keep the open/close tags in the same line
    – Jason
    Feb 5, 2014 at 2:06
  • +1. @Jason - unclear what is you comment "keep the open/close tags in the same line" is about... There is nothing in the answer that adds extra new lines... Feb 5, 2014 at 2:11
  • Thanks Steve, the second example if what I'm looking for
    – Jason
    Feb 5, 2014 at 2:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.