Regex logical OR

c#, regex

Solution

Your regex doesn't know where to start or stop the alternativ options separated by `|`. So you need to put them in subpatterns:

(id="|>).+?(">|</)

However, regex is not the right tool to parse XML.

Those round brackets also add capturing subpatterns. This can be returned by themselves. So this:

(id="|>)(.+?)(">|</)

will return the whole match at index 0, the front-delimiter at index 1, the actual match you want at index 2, and the last delimiter at index 3. In most regex engines you can do this:

(?:id="|>)(.+?)(?:">|</)

to avoid capturing the delimiters. Now index 0 will have the whole match, and index 1 only the 3 letters. Unfortunately, I can't tell you how to retrieve them in C#.

Problem

This is a purely academic exercise relating to regex and my understanding of grouping multiple patterns. I have the following example string ``` <xContext id="ABC"> <xData id="DEF"> <xData id="GHI"> <ID>JKL</ID> <str>MNO</str> <str>PQR</str> <str> <order id="STU"> <str>VWX</str> </order> <order id="YZA"> <str>BCD</str> </order> </str> </xContext> ``` Using C# Regex I'm attempting to extract the groups of 3 capital letters. At the moment if I use pattern `>.+?</` I get ``` Found 5 matches: >JKL</ >MNO</ >PQR</ >VWX</ >BCD</ ``` If I then use `id=".+?">` I get ``` Found 5 matches: id="ABC"> id="DEF"> id="GHI"> id="STU"> id="YZA"> ``` Now I'm trying to combine them by using logic OR `|` for each term on both sides `id="|>.+?">|</` However, this isn't giving me the combined results of both patterns My questions are: Can someone explain why this isn't working as expected? How can I correct the pattern to get both results shown combined in correct order listed How can I further enhance the combined pattern to just give letters only? I'm hoping it's still `?<=` and `?=<` but just want to check. Thank you

Original source

Related problems