-->

Replace symbol “%” with word “Percent”

2020-03-03 06:05发布

问题:

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

回答1:

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");


回答2:

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");


回答3:

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!-)



回答4:

In Java you can just use the % symbol it doesn't need to be escaped.

myString = myString.replaceAll("%", "Percent");

Or if like me converting so % could be rendered correctly as HTML

myString = myString.replaceAll("%", "%");