views:

173

answers:

4

Hi,

How to replace symbol "%" with a word "Percent".

My original string is "Internal (%) External (%)". The string should be "Internal (Percent) External (Percent)"

Using regular expression, how I can replace this symbol?

Thanks in advance. Atul

+4  A: 

You don't need a Regex here, you can use a regular replace. For example using .net:

string s = "Internal (%) External (%)";
s = s.Replace("%", "Percent");
Kobi
Whether or not a regex is required is dependent upon the environment, which is presently unspecified. In Javascript, for example, a regex is required if ALL occurrences need replacing.
csj
+1  A: 

Hi, the match string will simply be a percent symbol: %

However, implementing is specific to your regex environment.

Javascript

var myString = "Internal (%) External (%)";
myString = myString.replace(/%/g,"Percent");
csj
`%` does not have a special meaning and should not be escaped. Using JavaScript, `/%/` will work for the first character, make sure to add the `g` flag - `/%/g`
Kobi
@Kobi You're right, I don't need to escape it. Beat you to it with the global flag though. ;)
csj
+2  A: 

What language are you using? In many languages, you wouldn't need a regex for this, e.g., in Python...:

>>> "Internal (%) External (%)".replace('%','Percent')
'Internal (Percent) External (Percent)'

but if you did want to use RE for some peculiar reason, that would also be easy:

>>> import re
>>> re.sub('%', 'Percent', "Internal (%) External (%)")
'Internal (Percent) External (Percent)'

the details of performing such a global replacement, with REs or without them, will vary by language, so it's hard to offer specific help without knowing what language you're using!-)

Alex Martelli
A: 

How can i replace the ^ sybol.I have tried str.replace(/^/g."Cap");But its is not working.Please provide a better solution for this.

Thanks in advance...

This should be a separate question.
Kinopiko