Fx{r} is trying to start the Fx{r} Community! Please join our group on Adobe Groups following this link: http://groups.adobe.com/groups/ab29539ab9.
Fx{r} is now on Twitter too. Follow us @ twitter.com/fx_r!
«
»

ActionScript, How to, MXML, Regexp

How To Escape All Regexp Special Chars

Andrei Ionescu | 07.08.08 | 2 Comments

Google Buzz

This is a very helpful piece of code. Function to escape all regular expression special chars. I came to this string having this order of characters by trial and error. So now you can use it easily by copy and paste.

What is important to know that MXML and Actionscript compiler do automatically escapes backslashes (“\”) and because of this you may encounter a lot of problems with regular expression.

This piece of code makes use a lot of regular expression so to fully understand the expression you really need to get into regular expression “language”.

So here it is…

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
    layout="absolute" width="400" height="200">
    <mx:TextArea id="oldstr" text="{}()^$&amp;.*?-/+|[]\" 
        x="10" y="10" width="380" height="70"/>
    <mx:TextArea id="newstr" x="10" y="118" width="380" height="70"/>
    <mx:Button x="149" y="88" label="Escape string" 
        click="handleDoEscape(event)"/>
    <mx:Script>
        <![CDATA[
            // string to test with: {}()^$&.*?-/+|[]\
            private function escapeRegexChars(s:String):String
            {
                var newString:String = 
                    s.replace(
                        new RegExp("([{}\(\)\^$&.\*\?\/\+\|\[\\\\]|\]|\-)","g"),
                        "\\$1");
                return newString;
            }
 
            private function handleDoEscape(event:Event):void
            {
                newstr.text = escapeRegexChars(oldstr.text);
            }
        ]]>
    </mx:Script>
</mx:Application>

Easy codding… and learn Regexp!

Useful site for learning and more: http://www.regular-expressions.info/

Share and Enjoy:
  • Twitter
  • Google Buzz
  • LinkedIn
  • Google Bookmarks
  • del.icio.us
  • Digg
  • Sphinn
  • blogmarks
  • Reddit
  • StumbleUpon
  • Facebook
  • DZone
  • FriendFeed
  • Yahoo! Buzz
  • Yahoo! Bookmarks
  • Slashdot
  • MySpace
  • Add to favorites




Tags: , , ,

This post was written by Andrei Ionescu

Views: 5947

related

2 Comments

have your say

Add your comment below, or trackback from your own site. Subscribe to these comments.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

:

:


«
»