This is always a neat trick that I seem to always forget about, so I thought I’d post it here. When working with Regular Expressions, the RegExp class supports named groups. So instead of having to go through the RegExp result and access it like an array ([1], [2] .. [n]), you can use named results. Long story short, it can make working with the results a bit more intuitive. I made a simple example below which parses the user’s Flash Player version and displays the operating system/platform, major revision, minor revision, build number and internal build number.
Full code after the jump.
<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/08/22/using-named-groups-with-regular-expressions/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white"
creationComplete="init()">
<mx:Script>
<![CDATA[
import flash.system.Capabilities;
private function init():void {
var pattern:RegExp = /^(?P<platform>(\w+)) (?P<majorVersion>(\d+)),(?P<minorVersion>(\d+)),(?P<buildNumber>(\d+)),(?P<internalBuildNumber>(\d+))$/i;
versionObject = pattern.exec(Capabilities.version);
}
]]>
</mx:Script>
<mx:Object id="versionObject">
<mx:platform></mx:platform>
<mx:majorVersion></mx:majorVersion>
<mx:minorVersion></mx:minorVersion>
<mx:buildNumber></mx:buildNumber>
<mx:internalBuildNumber></mx:internalBuildNumber>
</mx:Object>
<mx:Panel title="Capabilities.version: {Capabilities.version}"
dropShadowEnabled="false"
cornerRadius="0"
borderColor="haloSilver"
backgroundColor="haloSilver"
borderAlpha="1.0">
<mx:Label text="platform: {versionObject.platform}" />
<mx:Label text="majorVersion: {versionObject.majorVersion}" />
<mx:Label text="minorVersion: {versionObject.minorVersion}" />
<mx:Label text="buildNumber: {versionObject.buildNumber}" />
<mx:Label text="internalBuildNumber: {versionObject.internalBuildNumber}" />
</mx:Panel>
</mx:Application>
View source is enabled in the following example.
For more information on using groups with Regular expressions, see the “Using named groups” documentation in the Flex Programming ActionScript 3.0 book.





0 Responses to “Using named groups with Regular Expressions”
Leave a Reply