0

I'm attempting to build a regular expression that will match against the contents of an XML element containing some un-encoded data. Eg:

<myElement><![CDATA[<p>The <a href="http://blah"> draft </p>]]></myElement>

Usually in this circumstance I'd use

[^<]*

to match everything up to the less than sign but this isn't working in this case. I've also tried this unsuccessfully:

[^(</myElement>)]*

I'm using Groovy, i.e. Java.

Fergal
  • 5,213
  • 6
  • 35
  • 44
  • 3
    Wait for it... http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – BoltClock Apr 08 '11 at 04:42
  • 1
    Haha, thanks BoltClock.... "asking regexes to parse arbitrary HTML is like asking Paris Hilton to write an operating system" – Fergal Apr 08 '11 at 04:49

2 Answers2

3

Please don't do this, but you're probably looking for:

<myElement>(.*?)</myElement>

This won't work if <myElement> (or the closing tag) can appear in the CDATA. It won't work if the XML is malformed. It also won't work with nested <myElement>s. And the list goes on...

The proper solution is to use a real XML parser.

Your [^(</myElement>)]* regex was saying: match any number of characters that are not in the set (, <, /, m, etc., which is clearly not what you intended. You cannot place a group within a character class in order for it to be treated atomically -- the characters will always be treated as a set (with ( and ) being literal characters, too).

Cameron
  • 96,106
  • 25
  • 196
  • 225
0

if you are doing it on a line by line basis, this will match the inside if your example:

>(.*)</

returns: <![CDATA[<p>The <a href="http://blah"> draft </p>]]>

Probably use it something like this:

subjectString = '<myElement><![CDATA[<p>The <a href="http://blah"> draft </p>]]></myElement>';
Matcher regexMatcher = subjectString =~ ">(.*)</"
if (regexMatcher.find()) {
    String ResultString = regexMatcher.group();
} 
Jim Wolff
  • 5,052
  • 5
  • 34
  • 44