tags:

views:

44

answers:

2

Hi,

I need some Regex help.

I need to find beacon_ followed by an alphanumeric code and then wrap it in quotation marks. For something static, like the example, below it's straight forward.

myReturn = myReturn.replace( 'id=beacon_80291ee9b3', 'id="beacon_80291ee9b3"');

But, my problem is that the part after beacon is a random alphanumeric code. (However, it is always the same length). For example, the beacon part could be:

  • beacon_c8ac873136

  • beacon_dc83b5953e

  • beacon_7a910d03d8

etc.

The haystack that I'll search will look like:

myReturn = "blah blah id=beacon_80291ee9b3 blah blah";

Thanks.

-Laxmidi

A: 
myReturn = myReturn.replace('id=beacon_(\w{10})', 'id="beacon_$1"');
Alan Moore
Hi Alan,Thank you for the help. Much appreciated.-Laxmidi
Laxmidi
A: 

You use a set like [0-9a-z] to match an alphanumeric character, and use {10} to specify how many. Use parentheses to specify what to match, and $1 to use the match in the replacement:

myReturn = myReturn.replace('id=(beacon_[0-9a-z]{10})', 'id="$1"');
Guffa
Hi Guffa,Thank you! It worked perfectly. And I appreciated the explanation.-Laxmidi
Laxmidi