Edit

6 years after my original answer (below) I would solve this problem differently

function mreplace (replacements, str) {
  let result = str;
  for (let [x, y] of replacements)
    result = result.replace(x, y);
  return result;
}

let input = 'Hello World what a beautiful day';

let output = mreplace ([
  [/Hello/, 'Bye'],
  [/World/, 'Universe']
], input);

console.log(output);
// "Bye Universe what a beautiful day"

This has as tremendous advantage over the previous answer which required you to write each match twice. It also gives you individual control over each match. For example:

function mreplace (replacements, str) {
  let result = str;
  for (let [x, y] of replacements)
    result = result.replace(x, y);
  return result;
}

let input = 'Hello World what a beautiful day';

let output = mreplace ([
  //replace static strings
  ['day', 'night'],
  // use regexp and flags where you want them: replace all vowels with nothing
  [/[aeiou]/g, ''],
  // use captures and callbacks! replace first capital letter with lowercase 
  [/([A-Z])/, 0.toLowerCase()]

], input);

console.log(output);
// "hll Wrld wht  btfl nght"


Original answer

Andy E's answer can be modified to make adding replacement definitions easier.

var text = "Hello World what a beautiful day";
text.replace(/(Hello|World)/g, function ($0){
  var index = {
    'Hello': 'Bye',
    'World': 'Universe'
  };
  return index[$0] != undefined ? index[0;
});

// "Bye Universe what a beautiful day";
Answer from maček on Stack Overflow
Top answer
1 of 5
16

Edit

6 years after my original answer (below) I would solve this problem differently

function mreplace (replacements, str) {
  let result = str;
  for (let [x, y] of replacements)
    result = result.replace(x, y);
  return result;
}

let input = 'Hello World what a beautiful day';

let output = mreplace ([
  [/Hello/, 'Bye'],
  [/World/, 'Universe']
], input);

console.log(output);
// "Bye Universe what a beautiful day"

This has as tremendous advantage over the previous answer which required you to write each match twice. It also gives you individual control over each match. For example:

function mreplace (replacements, str) {
  let result = str;
  for (let [x, y] of replacements)
    result = result.replace(x, y);
  return result;
}

let input = 'Hello World what a beautiful day';

let output = mreplace ([
  //replace static strings
  ['day', 'night'],
  // use regexp and flags where you want them: replace all vowels with nothing
  [/[aeiou]/g, ''],
  // use captures and callbacks! replace first capital letter with lowercase 
  [/([A-Z])/, 0.toLowerCase()]

], input);

console.log(output);
// "hll Wrld wht  btfl nght"


Original answer

Andy E's answer can be modified to make adding replacement definitions easier.

var text = "Hello World what a beautiful day";
text.replace(/(Hello|World)/g, function ($0){
  var index = {
    'Hello': 'Bye',
    'World': 'Universe'
  };
  return index[$0] != undefined ? index[0;
});

// "Bye Universe what a beautiful day";
2 of 5
14

You can pass a function to replace:

var hello = "Hello World what a beautiful day";
hello.replace(/Hello|World/g, function (1, 3, n for captures
{
    if ($0 == "Hello")
        return "Bye";
    else if ($0 == "World")
        return "Universe";
});

// Output: "Bye Universe what a beautiful day";
🌐
Medium
medium.com › @josemarmolejos › using-a-list-of-patterns-to-apply-multiple-regex-replacements-on-a-string-ec16dd5290e4
Using a list of patterns to apply multiple regex replacements on a string. | by Jose Marmolejos | Medium
May 25, 2016 - And passing a MatchEvaluator to the Regex.Replace() method (the last param in the call), I get to decide what to do with each match. So in my case I built a dictionary that held the matches and the replacement text, using the matched portion as a key.
Discussions

Can re.sub match multiple patterns and replace them differently (according to which pattern is matched)?
If you give some example input and expected output, it would help to understand your problem better. Does this example fit you use case? # one to one mappings >>> d = { '1': 'one', '2': 'two', '4': 'four' } >>> re.sub(r'1|2|4', lambda m: d[m[0]], '9234012') '9two3four0onetwo' # if the matched text doesn't exist as a key, default value will be used >>> re.sub(r'\d', lambda m: d.get(m[0], 'X'), '9234012') 'XtwoXfourXonetwo' More on reddit.com
🌐 r/learnpython
10
4
February 10, 2021
javascript - Multiple regex replacements
I receive a string with a lot of characters that I don't need and I am trying to remove them and replace them with characters that I am able to work with. My current structure has me redefining the... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
March 15, 2017
How do regular expressions replace multiple matches?
My regular expression pattern is: @"(Print)(?:.+)(?=information)" My replacement string is: “$1 a operation”. But the result is not correct... How to replace it? ... An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming. ... string sample = "Print Computer information"; string result = Regex... More on learn.microsoft.com
🌐 learn.microsoft.com
1
0
June 12, 2021
Regex > Replace Multiple words from input string
Hi There, I have a string #abc #bbc #xyz to be removed from string of(Note: #abc #bbc #xyz will be dynamic text and not static ) #abc #bbc #xyz #testcricket #football #basketball I am using regex replace activity by replacing with " ", it works when replacing only single word. More on forum.uipath.com
🌐 forum.uipath.com
8
0
February 17, 2022
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python regex replace multiple patterns
Python regex replace multiple patterns - Spark By {Examples}
May 31, 2024 - As you are working with the re module, you might find yourself in a situation where you want to replace multiple patterns in a string. This task may seem
🌐
Wipfli LLP
wipfli.com › insights › articles › tc-c-regex-multiple-replacements
How to c# regex replace multiple matches | Wipfli
April 1, 2026 - Regex.Replace(input, "&|"|<|>|'", delegate(Match m) { return xmlEntityReplacements[m.Value]; }) That bears better results, but you could be duplicating items in the pattern if they are already in the dictionary.
Top answer
1 of 2
4

First, since you already did so inside of your two last expressions, with the same replacement:

article = article.replace(/\r?\n|\r/g,"")
article = article.replace(/\$|\#|\[|\]/g, "")

I'm puzzled why you didn't simply put both in a unique regexp:

article = article.replace(/\r?\n|\r|\$|\#|\[|\]/g, "")

Then to integrate with the 1st one, you might choose to:

  • join the two distincts replacements in a single line:

    var article = a.replace(/ |\./g, "_").replace(/\r?\n|\r|\$|\#|\[|\]/g, "")
    
  • or use a map approach, either suche the one pointed by @greybeard's link, or like this way (even if it might look a bit too sohpisticated for only two cases):

    var replacements = new Map([
        [/ |\./g, '_'],
        [/\r?\n|\r|\$|\#|\[|\]/g, '']
        ]),
        article = a;
    replacements.forEach(function(value, key){
          article = article.replace(key, value);
        });
    

The most interesting aspect in this latter solution is that it may be easily expanded if more replacements are needed.


EDIT following a good suggestion from @Niet the Dark Absol.

As soon as there are several unique characters to look for, with the same replacement, this kind of regexp /(a|b|c)/ can be replaced by /[abc]/, which is both simpler and more efficient!

Any of the above proposed solutions can be improved this way, so the latter one becomes:

    var replacements = new Map([
        [/[ .]/g, '_'],
        [/[\r\n$#[\]]/g, '']
        ]),
        article = a;
    replacements.forEach(function(value, key){
          article = article.replace(key, value);
        });
2 of 2
1

You could define your pattern and replacement in an array. Then you can use reduce to carry the string through the array while replacing them.

let formatters= [
  {pattern: / |\./g, replacement: '_'},
  {pattern: /\r?\n|\r/g, replacement: ''},
  {pattern: /\$|\#|\[|\]/g, replacement: ''},
];

let article = formatters.reduce((a, f) => a.replace(f.pattern, f.replacement), a);
🌐
PYnative
pynative.com › home › python › regex › python regex replace pattern in a string using re.sub()
Python Regex Replace Pattern in a string using re.sub()
July 19, 2021 - The count must always be a positive integer if specified. .By default, the count is set to zero, which means the re.sub() method will replace all pattern occurrences in the target string. flags: Finally, the last argument is optional and refers to regex flags.
Find elsewhere
🌐
Alvin Alexander
alvinalexander.com › java › how-to-use-multiple-regex-patterns-replaceall-strings-in-java
How to use multiple regex patterns with replaceAll (Java String class) | alvinalexander.com
February 3, 2024 - scala> val cleanWords = words.map(_.replaceAll("[\\.$|,|;|']", "")) cleanWords: Array[String] = Array(My, dog, ate, all, of, the, cheese, why, I, dont, know) ... The combination of the brackets and pipe characters is what makes this work. It’s often hard to read regex patterns, so it may help to look at that multiple search pattern regex more generally, like this:
🌐
UiPath Community
forum.uipath.com › help › studio
Regex > Replace Multiple words from input string - Studio - UiPath Community Forum
February 17, 2022 - Hi There, I have a string #abc #bbc #xyz to be removed from string of(Note: #abc #bbc #xyz will be dynamic text and not static ) #abc #bbc #xyz #testcricket #football #basketball I am using regex replace activity by replacing with " ", it works when replacing only single word.
🌐
Flexiple
flexiple.com › python › python-regex-replace
Python regex: How to search and replace strings | Flexiple - Flexiple
First of all, let us understand ... to perform the operation. count: If the pattern occurs multiple times in the string, the number of times you want it to be replaced. The default value is 0. It is optional. flags: The regex flags are optional....
🌐
MUI Stack
muhimasri.com › blogs › how-to-replace-multiple-words-and-characters-in-javascript
How to Replace Multiple Words and Characters in JavaScript
December 6, 2021 - Im so glads to be alife in a beautiful worLd."; str = str.replace(/Helo|world|glads|alife|Im/g, matched => correction[matched]); console.log(str); // expected output: "Hello world! I'm so glad to be alive in a beautiful world." We can further improve this by creating a list of words dynamically from the correction object as follows: const reg = new RegExp(Object.keys(correction).join("|"), "g"); str = str.replace(reg, (matched) => correction[matched]);
🌐
O'Reilly
oreilly.com › library › view › python-cookbook › 0596001673 › ch03s15.html
Replacing Multiple Patterns in a Single Pass - Python Cookbook [Book]
July 19, 2002 - # requires Python 2.1 or later from _ _future_ _ import nested_scopes import re # the simplest, lambda-based implementation def multiple_replace(adict, text): # Create a regular expression from all of the dictionary keys regex = re.compile("|".join(map(re.escape, adict.keys( )))) # For each match, look up the corresponding value in the dictionary return regex.sub(lambda match: adict[match.group(0)], text)
Authors   Alex MartelliDavid Ascher
Published   2002
Pages   608
Top answer
1 of 4
1
  • Ctrl+H
  • Find what: ^(\w+,\h*)(\w+)(?:,\h*(\w+))?(?:,\h*(\w+))?(?:,\h*(\w+))?(?:,\h*(\w+))?(?:,\h*(\w+))?(?:,\h*(\w+))?(?:,\h*(\w+))?(?:,\h*(\w+))?(?:,\h*(\w+))?
  • Replace with: $1$2\n(?3$1$3)(?4\n$1$4)(?5\n$1$5)(?6\n$1$6)(?7\n$1$7)(?8\n$1$8)(?9\n$1$9)
  • TICK Match case
  • TICK Wrap around
  • SELECT Regular expression
  • UNTICK . matches newline
  • Replace all

Explanation:

^               # beginning of line
    (               # group 1
        \w+             # 1 or more word characters
        ,               # a comma
        \h*             # 0 or more horizontal spaces
    )               # end group 1
    (\w+)           # group 2, 1 or more word characters
    (?:             # non capture group
        \h*             # 0 or more horizontal spaces
        (\w+)           # group 3, 1 or more word characters
    )?              # end group, optional
(?:,\h*(\w+))?      # same as above
(?:,\h*(\w+))?      # same as above
(?:,\h*(\w+))?      # same as above
(?:,\h*(\w+))?      # ... 
(?:,\h*(\w+))?      # ... 
(?:,\h*(\w+))?      # ... 
(?:,\h*(\w+))?      # ... 
(?:,\h*(\w+))?      # ... 

Replacement:

$1              # content of group 1
$2              # content of group 2
\n              # line feed, you can use \r\n for Windows
(?3             # if group 3 exists
    $1              # content of group 1
    $3              # content of group 3
)               # endif
(?4\n$1$4)      # same as above
(?5\n$1$5)      # ...
(?6\n$1$6)      # ...
(?7\n$1$7)      # ...
(?8\n$1$8)      # ...
(?9\n$1$9)      # ...

Screenshot (before):

Screenshot (after):

2 of 4
2

That regex is way too complicated. By using an actual programming language, things will be much simpler.

Here I give an example in Python. Get Python here.

Say you have this input:

Chicago, ORD, MDW
NY, JFK, LGA, EWR
California, LAX, JWA, LGB, BUR

And you want to convert it to your given output:

Chicago, ORD
Chicago, MDW  
NY, JFK
NY, LGA
NY, EWR
California, LAX
California, JWA
California, LGB
California, BUR

It is simple, first split the string into lines, the split each line into list of strings by commas. Finally return the combination of the first element and every other element of the same list.

lines = """Chicago, ORD, MDW
NY, JFK, LGA, EWR
California, LAX, JWA, LGB, BUR"""

for line in lines.splitlines():
    lst = line.split(', ')
    first = lst[0]
    for e in lst[1:]:
        print(f'{first}, {e}')
🌐
litsupporttips
litigationsupporttipofthenight.com › single-post › regex-search-to-find-and-replace-multiple-strings
Regex search to find and replace multiple strings
July 30, 2023 - In order to find and replace multiple strings using regular expression you can use this format: Find: (FindA)|(FindB)|(FindC)...Replace: (?1ReplaceA)(?2ReplaceB)(?3ReplaceC)...However if the operation is run this way it will not take word boundaries ...