Java string replace vs replaceall

Java replace() vs replaceAll() Method

Java replace() vs replaceAll() Method | Java has various methods and functions to manipulate strings. The replace() and replaceAll() methods are one of them. Even though both replace() and replaceAll() methods are used to replace characters or sub-string in the given string but they work differently. Let us see the difference between them.

  1. public String replace(char oldChar, char newChar)
  2. public String replace(CharSequence oldChar, CharSequence newChar)
  3. public String replaceAll(String oldChar, String newChar)

The replace() method can replace one character with another character or it can replace a CharSequence with another CharSequence. It can’t replace based on the regular expression. The replaceAll() method can only replace one string with another string, where the first string is a regular expression.

The main difference between replace() and replaceAll() is:- replaceAll() replaces based on the regular expression but replace() method doesn’t.

replace() vs replaceAll() Java

This program shows the working of the replace() method.

Java Program, Python Program, Go Program
Jeve Lenguege, Python Lenguege, Go Lenguege

This program shows the working of the replaceAll() method.

Language
Java Language, Python Language, Go Language

Java replace() vs replaceAll() Performance

As a performance concern, the replace() function is much faster than the replaceAll() method because replace() method first compiles the regular expression pattern and then matches and finally replaces the character.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Источник

Разница между строкой replace() и replaceAll()

Какая разница между методами java.lang.String replace() и replaceAll()
кроме последующего использования regex? Для простых подстановок, например, замените . на / ,
есть ли разница?

В java.lang.String метод replace либо принимает пару char, либо пару CharSequence (из которых String является подклассом, поэтому он с удовольствием возьмет пару строк). Метод replace заменит все вхождения char или CharSequence . С другой стороны, оба аргумента String для replaceFirst и replaceAll являются регулярными выражениями (regex). Использование неправильной функции может привести к тонким ошибкам.

Q: Какая разница между методами java.lang.String replace() и replaceAll() , кроме того, что в дальнейшем используется регулярное выражение.

A: Просто регулярное выражение. Они оба заменяют все🙂

Также существует replaceFirst() (который принимает регулярное выражение)

Читайте также:  Календарь

Метод replace() перегружен, чтобы принимать как примитивные аргументы char , так и CharSequence в качестве аргументов.

Теперь, что касается производительности, метод replace() немного быстрее, чем replaceAll() , потому что последний сначала компилирует шаблон регулярного выражения, а затем сопоставляет его до окончательной замены, тогда как первый просто соответствует предоставленному аргументу и заменяет.

Так как мы знаем, что сопоставление шаблонов регулярных выражений является немного более сложным и, следовательно, медленнее, тогда предпочтительнее replace() over replaceAll() .

Например, для простых подстановок, как вы упомянули, лучше использовать:

Примечание: приведенные выше аргументы метода преобразования зависят от системы.

И replace() и replaceAll() заменяют все вхождения в String.

Примеры

Я всегда нахожу примеры полезными для понимания различий.

replace()

Используйте replace() если вы просто хотите заменить некоторый char другим char или некоторой String другой String (на самом деле CharSequence ).

Замените все вхождения символа x на o .

String myString = "__x___x___x_x____xx_"; char oldChar = 'x'; char newChar = 'o'; String newString = myString.replace(oldChar, newChar); // __o___o___o_o____oo_ 

Замените все вхождения струнной fish sheep .

String myString = "one fish, two fish, three fish"; String target = "fish"; String replacement = "sheep"; String newString = myString.replace(target, replacement); // one sheep, two sheep, three sheep 

replaceAll()

Используйте replaceAll() если вы хотите использовать шаблон регулярного выражения.

Замените любое число на x .

String myString = "__1_6____3__6_345____0"; String regex = "\\d"; String replacement = "x"; String newString = myString.replaceAll(regex, replacement); // __x_x____x__x_xxx____x 
String myString = " Horse Cow\n\n \r Camel \t\t Sheep \n Goat "; String regex = "\\s"; String replacement = ""; String newString = myString.replaceAll(regex, replacement); // HorseCowCamelSheepGoat 

Смотрите также

String replace(char oldChar, char newChar) 

Возвращает новую строку в результате замены всех вхождений oldChar в этой строке с помощью newChar.

String replaceAll(String regex, String replacement 

Заменяет каждую подстроку этой строки, которая соответствует данному регулярному выражению с указанной заменой.

  • Оба replace() и replaceAll() принимают два аргумента и заменяют все вхождения первой подстроки (первый аргумент) в строке со второй подстрокой (второй аргумент).
  • replace() принимает пару char или charsequence, а replaceAll() принимает пару регулярных выражений.
  • Неверно, что replace() работает быстрее, чем replaceAll(), поскольку оба используют один и тот же код в своей реализации Pattern.compile(регулярное выражение).matcher(это).replaceAll(замена);

Теперь возникает вопрос, когда использовать replace и когда использовать replaceAll().
Если вы хотите заменить подстроку на другую подстроку, независимо от места ее появления в строке, используйте replace(). Но если у вас есть определенные предпочтения или условия, такие как замена только тех подстрок в начале или конце строки, используйте replaceAll(). Вот несколько примеров, подтверждающих мою мысль:

String str = new String("==qwerty==").replaceAll("^==", "?"); \\str: "?qwerty==" String str = new String("==qwerty==").replaceAll("==$", "?"); \\str: "==qwerty?" String str = new String("===qwerty==").replaceAll("(=)+", "?"); \\str: "?qwerty?" 

Как указано в ответе wickeD, с replaceAll строка замены обрабатывается по-разному между replace и replaceAll. Я ожидал, что [3] и [4] будут иметь одинаковое значение, но они разные.

public static void main(String[] args) < String[] a = new String[5]; a[0] = "\\"; a[1] = "X"; a[2] = a[0] + a[1]; a[3] = a[1].replaceAll("X", a[0] + "X"); a[4] = a[1].replace("X", a[0] + "X"); for (String s : a) < System.out.println(s + "\t" + s.length()); >> 

Это отличается от perl, где замена не требует дополнительного уровня экранирования:

#!/bin/perl $esc = "\\"; $s = "X"; $s =~ s/X/$X/; print "$s " . length($s) . "\n"; 

Это может быть довольно неприятным, так как при попытке использовать значение, возвращаемое java.sql.DatabaseMetaData.getSearchStringEscape() с заменойAll().

Читайте также:  Front end for php

Старый поток, который я знаю, но я как бы новичок в Java и обнаруживаю одно из его странных вещей. Я использовал String.replaceAll() , но получаю непредсказуемые результаты.

Что-то вроде этого испортит строку:

sUrl = sUrl.replaceAll( "./", "//").replaceAll( "//", "/"); 

Итак, я разработал эту функцию, чтобы обойти эту странную проблему:

//String.replaceAll does not work OK, that why this function is here public String strReplace( String s1, String s2, String s ) < if((( s == null ) || (s.length() == 0 )) || (( s1 == null ) || (s1.length() == 0 ))) < return s; >while( (s != null) && (s.indexOf( s1 ) >= 0) ) < s = s.replace( s1, s2 ); >return s; > 
sUrl=this.strReplace("./", "//", sUrl ); sUrl=this.strReplace( "//", "/", sUrl ); 

В Java существует два метода replace(), один из которых принимает символ как первый параметр, а другой принимает CharSequence (который является супер интерфейсом для String, Stringbuffer и т.д.) В качестве первого параметра. Оба этих метода заменяют все вхождения char или CharSequence значением, которое вы предоставляете во втором параметре.

Метод ReplaceAll принимает регулярное выражение как первый параметр, поэтому вам нужно дать ему некоторое Regex, и совпадающее содержимое будет заменено строкой, переданной во втором параметре.

Для полной разницы между методом replace() и replaceAll() вы можете ссылаться здесь. Разница между методами replace(), replaceAll() и replaceFirst() в Java String

replace() метод не использует шаблон regex, тогда как метод replaceAll() использует шаблон регулярного выражения. Поэтому replace() выполняется быстрее, чем replaceAll() .

replace and replaceAll меняет string и char во всех словах, но replaceAll поддерживает регулярное выражение (регулярное выражение). Существует также replaceFirst которая похожа на replaceAll на то, что они поддерживают регулярное выражение, а также строки изменения и символы, разница между ними заключается в том, что при использовании replaceFirst с регулярным выражением он заменяет первое регулярное выражение ТОЛЬКО.

// Java_codes_for_more_explanation ; String name1 = "Omar Ahmed Hafez" ; name1 = name1.replace("Omar", "Ahmed"); System.out.println(name1); ///////////////////////////////////////////// String name2 = "Omar Ahmed Hafez" ; name2 = name2.replaceAll("\\s", "-"); // The first parameter("\\W") is regex and it mean replace #ALL // space by "-" and it change All regex in the line as its replaceALL System.out.println(name2); //////////////////////////////////////////// String name3 = "Omar Ahmed Hafez" ; name3 = name3.replaceFirst ("\\s", "-"); // The first parameter("\\W") is regex and it mean replace #FIRST // space ONLT by "-" (as //it replaceFirst so it replace the first // regex only :) System.out.println(name3); 
Ahmed Ahmed Hafez Omar-Ahmed-Hafez 

заменить работы на тип данных char, но replaceAll работает с типом данных String и заменяет все вхождения первого аргумента вторым аргументом.

Источник

Java replace vs replaceall – How to replace a String in Java? | Java.lang.string.replace() method in Java | replace() vs replaceAll() vs replaceFirst()

How to replace a String in Java

Java replace vs replaceall: In our previous tutorial, we have seen & got an explanation on how to find the string length in java using length method. And today, we have come up with a new tutorial that helps to replace a string in java. Hence, we will learn completely about how to replace a string in java?

Читайте также:  Kotlin константы времени компиляции

Also, you will find the difference between replace(), replaceAll(), and replaceFirst() methods. So, follow the available links and start understanding the concept of replacing strings in java quickly.

How to Replace a String in Java?

Replace vs replaceall java: There are three Java String methods that are mainly utilized for the replacement of a string with another string. They are as such:

All three can be helpful in illustrating how to replace a string in java. So, have a look at the first java string replace() method with an example and then continue with the other two methods too.

1. Java.lang.string.replace() method in Java

Java string replace vs replaceall: The replace() method of the String class is used to replace all the occurrences of an old character in this string with a new character.

The syntax of the string replace() method is given below:

public String replace(char oldChar, char newChar)

Here, oldChar specifies the characters to be replaced by the character specified by newChar.

Example of Java String replace() Method:

2. replaceAll() method in Java

Replace vs replaceall: This method returns a String that replaces each substring with this string that matches the given regular expression with the given replacement.

The syntax of the replaceAll() method is given below:

public String replaceAll(String regex, String replacement)

Example of Java String replaceAll() method:

String Tutorial by java StringTutorialisjava.

Remember that, it throws PatternSyntaxException if the regular expression syntax is invalid. Let’s see the example.

How to replace a String in Java 1

3. replaceFirst() method in Java

This method is applied to replaces the first substring of this string that meets the given regular expression with the given replacement. It throws PatternSyntaxException if the regular expression is invalid.

The syntax of the replaceFirst() method is given below:

public String replaceFirst(String regex, String replacement)

Example of Java replaceFirst() method:

String Tutorial by Lavanya

replace() vs replaceAll() vs replaceFirst()

The main difference between replace(), replaceAll(), and replaceFirst() methods are listed below:

  • The difference between replace() and replaceAll() method is that the replace() method replaces all the events of the old char with the new char whereas the replaceAll() method replaces all the events of an old string with the new string.
  • Fundamentally, replace() operates with replacing chars and replaceAll() operates with replacing part of strings.
  • When it comes to the difference between replaceFirst() and replaceAll() method. The replaceFirst() replaces the first occurrence while replaceAll() replaces all the occurrences.

Источник

Оцените статью