4

How can I include a dynamic variable into a regexp object?

var pattern:RegExp = new RegExp(/'a '/ + keyword, '/gi');

In this case, I'd like the regex to match "a bird", or "A biRD" (if 'bird' is the keyword). However, 'bird' should not match if it is on its own.

Furthermore, I have a follow up question (I hope it's not too much to ask!): How would I do the exact thing above, but in which the regex only matches if the keyword is NOT preceded by 'a ' (I believe this involves the use of the ^ or the !, but I can't seem to find any clear documentation in any language for my specific request).

In the case of my second question test cases would look like this:

WORKS

abird
bird
bbbbirdddd

DOESN'T WORK

a bird
a birdddd

Any help will be greatly appreciated!

Olin Kirkland
  • 548
  • 4
  • 23

1 Answers1

1

ActionScript 3.0 supports lookbehinds and the case-insensitive modifier:

/(?<=a\s+)bird/i

See here for more information on how to construct a regular expression from a variable: Using a Variable in an AS3, Regexp.

For the second part of your question:

/(?<!a\s+)bird/i
Community
  • 1
  • 1
Andrew Cheong
  • 29,362
  • 15
  • 90
  • 145
  • What if instead of "a ", I wanted a longer phrase? Such as "a blue "? – Olin Kirkland Sep 04 '12 at 17:49
  • The lookbehind takes any regular expressions atom! So, you can even do this: ``/(?<!a big blue )bird/i``. (And replace the spaces with ``\s+`` for whitepsace flexibility.) (I recall hearing that some regex engines only allow fixed-width lookbehinds; in that case you may not be able to use quantifiers within the lookbehind. Not sure if this is the case with AS3.) – Andrew Cheong Sep 04 '12 at 17:53
  • What if "bird" is a dynamic variable? (Bird is just an example of a keyword) – Olin Kirkland Sep 04 '12 at 18:02
  • never mind. i'm making it a string, then just using the string as one to pass to the regex. – Olin Kirkland Sep 04 '12 at 18:14
  • As shown in the link I provided, you have to build a new RegExp object from a string. ``var str:String = '(?<!a\s+)' + yourDynamicVariable; var regex:Regexp = new RegExp(str, 'i');`` – Andrew Cheong Sep 04 '12 at 18:15