views:

95

answers:

3
+1  A: 

You should look into methods other than regular expressions to parse XML, particularly if:

  • your requirements are likely to change in future, making your regular expression increasingly unweildy
  • you are parsing data from a third-party source, which may contain just about anything, including strings that look like XML tags embedded in XML comments, CDATA sections or attributes.

See this answer for information about XML parsing in Javascript.

The easy solution is "use jQuery". If for some reason you don't want to load jQuery to do this, then start here.

thomasrutter
+1  A: 

You can use the regex "|" operator (meaning "or") to create a regex that will match one or more expressions. For example ...

/^<failed>[\w|\W]*?<\/failed>|^<pattern[^>]*>/

... should do what you're asking (based on the example you've given above).

But, as other commenters have said, parsing XML with regexs is a slippery slope. You'll probably want to look into other options, like using the DocumentFragment class to parse your string for you.

broofa
Thanks broofa, your answer does exactly as I wanted. I understand others' concern, but the file structure is unlikely to change in the future (I added more comments). I am inclined to use regex.
Michael Z
Hi broofa, sorry I slightly edited my question, your regular expression worked perfectly well for my original requirement, any chance you can have a at the new text to be parsed?
Michael Z
+1  A: 

Here are the RegExp you need:

<(pattern|failed)\b[^>]*(?:/>|>[^<]*</\1>)

Just escape the slashes when using in Javascript regular expression notation:

var regExp = /<(pattern|failed)\b[^>]*(?:\/>|>[^<]*<\/\1>)/gi;
var matchesArray = testString.match(regExp);

This regular expression will find whole <pattern> and <failed> tags, either if they are empty tags or not (<empty/> or <notEmpty></notEmpty>). It also considers possible element attributes.

smnh
Hi smnh, sorry I slightly edited my question, your regular expression worked perfectly well for my original requirement, any chance you can have a at the new text to be parsed?
Michael Z