Replace multiple strings with multiple other strings
As an answer to:
looking for an up-to-date answer
If you are using "words" as in your current example, you might extend the answer of Ben McCormick using a non capture group and add word boundaries \b
at the left and at the right to prevent partial matches.
\b(?:cathy|cat|catch)\b
\b
A word boundary to prevent a partial match(?:
Non capture groupcathy|cat|catch
match one of the alternatives
)
Close non capture group\b
A word boundary to prevent a partial match
Example for the original question:
let str = "I have a cat, a dog, and a goat.";
const mapObj = {
cat: "dog",
dog: "goat",
goat: "cat"
};
str = str.replace(/\b(?:cat|dog|goat)\b/gi, matched => mapObj[matched]);
console.log(str);
How to replace multiple substrings of a string?
Here is a short example that should do the trick with regular expressions:
import re
rep = {"condition1": "", "condition2": "text"} # define desired replacements here
# use these three lines to do the replacement
rep = dict((re.escape(k), v) for k, v in rep.iteritems())
#Python 3 renamed dict.iteritems to dict.items so use rep.items() for latest versions
pattern = re.compile("|".join(rep.keys()))
text = pattern.sub(lambda m: rep[re.escape(m.group(0))], text)
For example:
>>> pattern.sub(lambda m: rep[re.escape(m.group(0))], "(condition1) and --condition2--")
'() and --text--'
How to replace multiple values at once
A possible solution using match
:
old <- 1:8
new <- c(2,4,6,8,1,3,5,7)
x[x %in% old] <- new[match(x, old, nomatch = 0)]
which gives:
> x
[1] 8 4 0 5 1 5 7 9
What this does:
- Create two vectors:
old
with the values that need to be replaced andnew
with the corresponding replacements. - Use
match
to see where values fromx
occur inold
. Usenomatch = 0
to remove theNA
's. This results in an indexvector of the position inold
for thex
values - This index vector can then be used to index
new
. - Only assign the values from
new
to the positions ofx
that are present inold
:x[x %in% old]
How to use str.replace to replace multiple pairs at once?
You can create a dictionary and pass it to the function replace()
without needing to chain or name the function so many times.
replacers = {',':'','.':'','-':'','ltd':'limited'} #etc....
df1['CompanyA'] = df1['CompanyA'].replace(replacers)
Replace multiple characters in one replace call
If you want to replace multiple characters you can call the String.prototype.replace()
with the replacement argument being a function that gets called for each match. All you need is an object representing the character mapping that you will use in that function.
For example, if you want a
replaced with x
, b
with y
, and c
with z
, you can do something like this:
const chars = {'a':'x','b':'y','c':'z'};
let s = '234abc567bbbbac';
s = s.replace(/[abc]/g, m => chars[m]);
console.log(s);
Output: 234xyz567yyyyxz
Pandas replace multiple values at once
try .replace({}, regex=True)
method:
replacements = {
'CITY': {
r'(D.*DO|DOLLARD.*)': 'DOLLARD-DES-ORMEAUX',
r'I[lL]*[eE]*.*': 'ILLE Perot'}
}
df.replace(replacements, regex=True, inplace=True)
print(df)
Output:
SURNAME ADDRESS CITY
0 Jenson 252 Des Chênes DOLLARD-DES-ORMEAUX
1 Jean 236 Gouin DOLLARD-DES-ORMEAUX
2 Denis 993 Boul. Gouin DOLLARD-DES-ORMEAUX
3 Bradford 1690 Dollard #7 DOLLARD-DES-ORMEAUX
4 Alisson 115 Du Buisson ILLE Perot
5 Abdul 9877 Boul. Gouin Pierrefonds
6 O'Neil 5 Du College ILLE Perot
7 Bundy 7345 Sherbrooke ILLE Perot
8 Darcy 8671 Anthony #2 ILLE Perot
9 Adams 845 Georges Pierrefonds
Replace multiple strings at once
You could extend the String object with your own function that does what you need (useful if there's ever missing functionality):
String.prototype.replaceArray = function(find, replace) {
var replaceString = this;
for (var i = 0; i < find.length; i++) {
replaceString = replaceString.replace(find[i], replace[i]);
}
return replaceString;
};
For global replace you could use regex:
String.prototype.replaceArray = function(find, replace) {
var replaceString = this;
var regex;
for (var i = 0; i < find.length; i++) {
regex = new RegExp(find[i], "g");
replaceString = replaceString.replace(regex, replace[i]);
}
return replaceString;
};
To use the function it'd be similar to your PHP example:
var textarea = $(this).val();
var find = ["<", ">", "\n"];
var replace = ["<", ">", "<br/>"];
textarea = textarea.replaceArray(find, replace);
Related Topics
Getting the Column Names of a Data Frame with Sapply
Boxplot, How to Match Outliers' Color to Fill Aesthetics
R Plots: How to Draw a Border, Shadow or Buffer Around Text Labels
Remove Certain Legend Variables and Legend Values from Ggplot2
R - Cumulative Sum by Condition
Retain Attributes When Using Gather from Tidyr (Attributes Are Not Identical)
How to Create a Variable of Rownames
Efficient Multiplication of Columns in a Data Frame
Getting File Path from Shiny UI (Not Just Directory) Using Browse Button Without Uploading the File
Navlistpanel: Make Tabs Sequentially Active in Shiny App
Change Color Median Line Ggplot Geom_Boxplot()
How to Reverse Legend (Labels and Color) So High Value Starts at Bottom
Remove Certain Legend Variables and Legend Values from Ggplot2
Ggplot2: How to Transparently Shade Alternate Days on a Plot
How to Apply a Gradient Fill to a Geom_Rect Object in Ggplot2