Replacing All Occurrences of a Pattern in a String

How do I replace all occurrences of a string in JavaScript?

In the latest versions of most popular browsers, you can use replaceAll
as shown here:

let result = "1 abc 2 abc 3".replaceAll("abc", "xyz");
// `result` is "1 xyz 2 xyz 3"

But check Can I use or another compatibility table first to make sure the browsers you're targeting have added support for it first.


For Node.js and compatibility with older/non-current browsers:

Note: Don't use the following solution in performance critical code.

As an alternative to regular expressions for a simple literal string, you could use

str = "Test abc test test abc test...".split("abc").join("");

The general pattern is

str.split(search).join(replacement)

This used to be faster in some cases than using replaceAll and a regular expression, but that doesn't seem to be the case anymore in modern browsers.

Benchmark: https://jsben.ch/TZYzj

Conclusion:

If you have a performance-critical use case (e.g., processing hundreds of strings), use the regular expression method. But for most typical use cases, this is well worth not having to worry about special characters.

how to replace all occurrences of a string inside tags using regex in java

We can try using a formal regex pattern matcher here. Match on the pattern <abc~a>(.*?)<abc~a>, and for each match append the tag with src replaced by abc. Here is a sample code:

String input = "Here is a src <abc~a>I am an src customer<abc~b> also another src here.";
Pattern p = Pattern.compile("<abc~a>(.*?)<abc~b>");
Matcher m = p.matcher(input);
StringBuffer buffer = new StringBuffer();

while(m.find()) {
String replace = "<abc~a>" + m.group(1).replaceAll("\\bsrc\\b", "abc") + "<abc~b>";
m.appendReplacement(buffer, replace);
}
m.appendTail(buffer);

System.out.println(buffer.toString());

This prints:

Here is a src <abc~a>I am an abc customer<abc~b> also another src here.

Note that in many other languages we could have used a regex callback function. But core Java does not support this functionality, so we have to iterate over the entire input.

Fastest method to replace all instances of a character in a string

The easiest would be to use a regular expression with g flag to replace all instances:

str.replace(/foo/g, "bar")

This will replace all occurrences of foo with bar in the string str. If you just have a string, you can convert it to a RegExp object like this:

var pattern = "foobar",
re = new RegExp(pattern, "g");

regex: how to replace all occurrences of a string within another string, if the original string matches some filter

Your regex only replaces the 456 that is at the start of the string that only consists of digits.

You may use

s/(?:\G(?!^)|^(?=\d+$))\d*?\K456/999/g

See the regex demo

Pattern details

  • (?:\G(?!^)|^(?=\d+$)) - a custom boundary that matches either the end of the previous successful match (\G(?!^)) or (|) the start of string (^) that only contains digits ((?=\d+$))
  • \d*? - 0+ digits, but as few as possible
  • \K - omit the currently matched chars
  • 456 - a 456 substring.

The idea is:

  • Use the \G based pattern to pre-validate the string: (?:\G(?!^)|^(?=<YOUR_VALID_LINE_FORMAT>$))
  • Then adjust the consuming pattern after the above one.

Replace all occurrences of substring in a string - which is more efficient in Java?

String.replace() uses regex underneath.

public String replace(CharSequence target, CharSequence replacement) {
return Pattern.compile(target.toString(), Pattern.LITERAL)
.matcher(this ).replaceAll(
Matcher.quoteReplacement(replacement.toString()));
}

Are there more efficient ways than the above described two?

There are given that you operate on an implementation backed e.g., by an array, rather than the immutable String class (since string.replace creates a new string on each invocation). See for instance StringBuilder.replace().

Compiling a regex incurs quite alot of overhead which is clear when observing the Pattern source code. Luckily, Apache offers an alternative approach in StringUtils.replace() which according to the source code (line #3732) is quite efficient.

Replacing all occurrences of a pattern in a string

The second line from ?sub explains:

sub and gsub perform replacement of the first and all matches respectively.

which should tell you to use gsub instead.

Replace all occurrences in a string by another string

You can use re.sub() to replace all occurrences of that pattern.

import re

s = "1 - 2 P_1(x) + 3 P_2(x) - 708.4250106547449 P_3(x)"

pattern = r' P_(\d+)\(x\)' # (\d+) captures the n in P_n
replace = r' * (x**\1)' # \1 uses the last captured n as a replacement

s_2 = re.sub(pattern, replace, s)
print(s_2)

Output:

1 - 2 * (x**1) + 3 * (x**2) - 708.4250106547449 * (x**3)

And with your full input:

s_3 = """487351.25373014854 - 152956.2387091797 P_1(x) +
14288.881396831219 P_2(x) - 708.4250106547449 P_3(x) +
22.029508388530736 P_4(x) - 0.46451906903633394 P_5(x) +
0.006931166409021728 P_6(x) - 7.493824771409185e-05 P_7(x) +
5.934862864562062e-07 P_8(x) - 3.442722590115344e-09 P_9(x) +
1.4457000568406937e-11 P_10(x) - 4.276159814629395e-14 P_11(x) +
8.446505496408776e-17 P_12(x) - 9.998295324026605e-20 P_13(x) +
5.362954837187194e-23 P_14(x)
"""

s_4 = re.sub(pattern, replace, s_3)
print(s_4)

Output:

487351.25373014854 - 152956.2387091797 * (x**1) +
14288.881396831219 * (x**2) - 708.4250106547449 * (x**3) +
22.029508388530736 * (x**4) - 0.46451906903633394 * (x**5) +
0.006931166409021728 * (x**6) - 7.493824771409185e-05 * (x**7) +
5.934862864562062e-07 * (x**8) - 3.442722590115344e-09 * (x**9) +
1.4457000568406937e-11 * (x**10) - 4.276159814629395e-14 * (x**11) +
8.446505496408776e-17 * (x**12) - 9.998295324026605e-20 * (x**13) +
5.362954837187194e-23 * (x**14)

Python, replace all occurrences of the pattern in a string

In your code, you are not saving the modified string. It is just changing the raw string every time and saving only one change.
Try like this:

string = "[link1], [link2], [link3]"

INPUT = input('Give the input').split(',')

replacer = {'1' : 'ONE', "2" : 'Two', '3' : 'Three'}

for i in INPUT:
string = string.replace(f'[link{i}]', replacer[i])

print(string)

replace all occurrences in a string

Use the global flag.

str.replace(/\n/g, '<br />');

Replacing all overlapping patterns in a string

You can use lookarounds to find values without including them in the match:

s = re.sub(r"(?<=0)1(?=0)", "X", s)

(?<=0)1(?=0) matches a single 1 character that is preceded – (?<=…)
and followed – (?=…) – by a zero.



Related Topics



Leave a reply



Submit