help with actionscript 3 regex and xmpp stanzas – Education Career Blog

i have a string:

<presence to="[email protected]/d9ec56e4"
from="[email protected]/testsubject_2">
<x xmlns="http://jabber.org/protocol/muc#user"><item affiliation="none"
role="visitor"/></x></presence>

how would i find out if it contains the presence attribute as well as who its from?
ive tried using as3’s xml methods but they require that the xml is a complete document so i figure to use regex but its late and im lost so ill post before i go to sleep 🙂

if (string contains <presence to="){
    // get who its from
}

,

ARGH! I would highly recommend you don’t use regex to parse XML, that’s why we have XML parsers.

var raw_data:String = '<presence to="[email protected]/d9ec56e4" from="[email protected]/testsubject_2"> <x xmlns="http://jabber.org/protocol/muc#user"><item affiliation="none" role="visitor"/></x></presence>';
trace("raw_data:", raw_data);
var presence:XML = new XML(raw_data);
trace("presence:", presence);
trace("root name == presence:", (presence.localName() == "presence")); // trace root name == presence: true
trace("from:", [email protected]); // trace from: [email protected]/testsubject_2

http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/XML.html

Or just use one of the many XMPP libraries out there:

http://code.google.com/p/as3xmpp/

http://code.google.com/p/seesmic-as3-xmpp/

,

/<(\w+)(( to|from)=\"(^\"+)\")+>.*</\1>/

,

Search for: /<presence\b(?=^><*\sto\s*=)^><*\sfrom\s*=\s*"'(^><"'*)"'.*?</presence>/gis

$1 will refer to who its from, e.g. [email protected]/testsubject_2

It works even if to/from in a different order.
It works even if XML uses single quotes, but there must not be a single-quotes between single-quotes. I can improve this behaviour further, but the regex would become longer.

If you take malformed XML documents into account, you shouldn’t use regex, use either DOM or XPath instead.

Leave a Comment