Regex pattern for replacing all special characters with space except those betwee quotes

StackOverflow https://stackoverflow.com/questions/22498141

  •  17-06-2023
  •  | 
  •  

Pregunta

I need a Regex pattern in salesforce to replace all special characters in a string except those between quotes like..

input: hai@#$welcome to 'World@#$'
output: hai welcome to 'World@#$'

I tried the following, but it's not working as expected:

'[^\\w((?<=\')(.*)(?=\'))]'
¿Fue útil?

Solución

Your search regex should be:

[^\w\s'](?=(([^']*'){2})*[^']*$)

And replace with:

" "

Online Demo: http://regex101.com/r/lC6zG5

Explanation:

enter image description here enter image description here

Otros consejos

use this [^\w\s\'](?=(([^']*'){2})*[^']*$)

same as Anubhavas answer, just a minor change to exclude the '

demo here : http://regex101.com/r/iL7oH7

manoj, resurrecting this question because there's one tidy solution that wasn't mentioned. This problem is a classic case of the technique explained in this question to "regex-match a pattern, excluding..."

We can solve it with a beautifully-simple regex:

'[^']*'|([^\w'\s]+)

The left side of the alternation | matches complete quoted strings. We will ignore these matches. The right side matches and captures special characters to Group 1, and we know they are the right ones because they were not matched by the expression on the left.

All that's left to do is to replace the match with an empty string, but only when Group 1 is set. The way do to this is different in every language, but it's not complex. The question and article below fully explain the technique (the article has code samples).

On this demo, if you look in the right pane, you can see how Group 1 only captures the chars you want to replace.

Reference

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top