views:

37

answers:

2

Hi,

I'm trying to replace different parts of a html code using a single regexp.

For exemple i have this text :

option_!!NID!! [somme_text][5] some_text_option 5_option_some_text

using this regexp:

content.replace(/(!!NID!!)|\[(\d)\]|(\d)_option/g, 1))

I expect to get :

option_1 [somme_text][1] some_text_option 1_option_some_text

but I have :

option_1 [somme_text]1 some_text_option 1_some_text

Can some one tell me how to do what i want, using a single regexp ?? Because i don't understand why the replace doesn't only replace the target between the parenthesis.

Thanks :)

PS : I'm using Ror so a ruby and JS solution is also possible.

A: 

The whole match is replaced. That means you need to handle cases differently:

"option_!!NID!! [somme_text][5] some_text_option 5_option_some_text".
    replace(/!!NID!!/g, "1").
    replace(/\d_option/g, "1_option").
    replace(/\[\d\]/g, "[1]")

The first and second case can then be combined using a look-ahead assertion for the second one:

"option_!!NID!! [somme_text][5] some_text_option 5_option_some_text".
    replace(/!!NID!!|\d(?=_option)/g, "1").
    replace(/\[\d\]/g, "[1]")
Gumbo
ye that's what i was trying to avoid :p
Niklaos
I found an alternative solution :) Thanks anyway.
Niklaos
A: 

Ok, I found a solution. It's a 2 step solution.

So, at the beginning I have :

option_!!NID!! [somme_text][5] some_text_option 5_option_some_text

First i'm doing a replacement on my string using the ruby method String.gsub :

str.gsub!(/\[(\d)\]|(\d_option)/) { |result| result.gsub(/\d/, '!!NID!!') }

After this step I have :

option_!!NID!! [somme_text][!!NID!!] some_text_option !!NID!!_option_some_text

I can now perform a simple replacement on the client side using JS.

content.replace(/(!!NID!!)/g, 1)

And voila :)

I've got now the expected result avoiding any ugly lines of JS.

I'm still looking for a better solution if you know one :)

Niklaos