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 OverflowEdit
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";
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";
Can re.sub match multiple patterns and replace them differently (according to which pattern is matched)?
javascript - Multiple regex replacements
How do regular expressions replace multiple matches?
Regex > Replace Multiple words from input string
I want to replace different patterns differently.
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);
});
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);
- 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):

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}')
You don't need a regex, you simply can use Replace:
string input = "this is a test AAA one more test adakljd jaklsdj BBB sakldjasdkj CCC";
string replaced = input.Replace("AAA", "XXX").Replace("BBB", "XXX")...
I suggest combining all patterns' parts ("AAA", ..., "CCC") with | ("or"):
string input = "this is a test AAA one more test adakljd jaklsdj BBB sakldjasdkj CCC";
string[] pattern = { "AAA", "BBB", "CCC" };
string replacement = "XXX";
string result = Regex.Replace(
input,
string.Join("|", pattern.Select(item => $"(?:{item})")),
replacement);
Console.WriteLine(result);
Outcome:
this is a test XXX one more test adakljd jaklsdj XXX sakldjasdkj XXX
I've turned each pattern part like BBB into a group (?:BBB) in case pattern part contains | within itself