-3

I am still learning Regex so help me out if I am wrong somewhere. In my project I am using simple formatted string to create a RichTextBlock through XAML Reader. I am able to format my string through some Regex patterns and now there is a problem that sometimes a <Hyperlink /> gets left out of the <Paragraph> tags and it throws exception.

The sample string for this is:

</Paragraph> some words here (@somevaluehere1)
                <Hyperlink NavigateUri="https://somelink.com">July 14, 2017</Hyperlink>

I want a Regex pattern to look out for this match:

if the opening TAG of <Hyperlink is right after the closing TAG of </Paragraph> then capture the string with whole Hyperlink value and replace it with surrounding <Paragraph> TAGs.

And the finished string should be like this, although I can replace the matched string with the use of Linq:

</Paragraph> some words here (@somevaluehere1)
                <Paragraph><Hyperlink NavigateUri="https://somelink.com">July 14, 2017</Hyperlink></Paragraph>

I want to know if it's possible to sort out this problem with Regex or do I need any other method.

I have made up a Regex pattern but I know it's not the right answer. Maybe someone with a little experience might help here.

The pattern I came up with is: <\/Paragraph>(\s?)(\w+\s?\w+\s?)(\(?\@?\w+\)?)(\s?<Hyperlink)

Ahmar
  • 740
  • 6
  • 26
  • 1
    Instead of abusing regex, you could [use Linq to replace a node in an XML](https://msdn.microsoft.com/en-us/library/bb302711(v=vs.110).aspx) instead. – LukStorms Jul 18 '17 at 11:45
  • Why do so many people try to use Regex to parse XML? – Manfred Radlwimmer Jul 18 '17 at 11:46
  • 1
    Possible duplicate of [Can you provide some examples of why it is hard to parse XML and HTML with a regex?](https://stackoverflow.com/questions/701166/can-you-provide-some-examples-of-why-it-is-hard-to-parse-xml-and-html-with-a-reg) – Manfred Radlwimmer Jul 18 '17 at 11:46

1 Answers1

0

You can do it like this: (<\/Paragraph>.*\s*)(<Hyperlink.*) and then replace by $1<Paragraph>$2</Paragraph>.

Working example: https://regex101.com/r/VfeTDd/3

Pedro Corso
  • 557
  • 8
  • 22