cancelar
Mostrando resultados para 
Pesquisar então 
Você quer dizer: 

replace single character and leave the ones in expressions

Resolvido!
Ir para a solução

Hi,

 

I'm looking for nice and elegant solution to my problem. Let's say I have a string "e+exp(e)". I want to replace all "e" with "1", excepts the one in "exp". I was trying to use regular expressions but I've failed after an hour... The solution should be able to solve things like replace "a" in "rand(a)" without changing rand. Basically I need to replace single character without replacing the ones in words/expressions.

 

Any ideas?  



0 Kudos
Mensagem 1 de 5
3.236Exibições
Solução
Aceita pelo autor do tópico pitol

No time for elegance right now, just brute force.  I would pad the string with spaces on each end to remove end cases and then search for the character surrounded by non-word characters. 

 

VariableParsingRegex.png

 

Message Edited by Darin.K on 04-14-2010 04:06 PM
Mensagem 2 de 5
3.223Exibições
Thanks! After looking at your solutions I must say that I was pretty close trying to solve it myself. Can you explain how those $1 and $2 works, that you put in replace char?


0 Kudos
Mensagem 3 de 5
3.197Exibições
If you look in the regular expression you will notice two expressions in parentheses, these are called capture groups.  In this case each one captures a non-word character.  To put those characters back in I put $1 and $2 into the replace string.  $n refers to the nth capture group inside the regex (comes from PERL so start counting at 1).  Very handy when you are looking to rearrange a string.
0 Kudos
Mensagem 4 de 5
3.173Exibições
Thanks again! It is indeed very handy 🙂 


0 Kudos
Mensagem 5 de 5
3.152Exibições