Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace string only once without regex in Java?

Tags:

java

string

I need to replace a dynamic substring withing a larger string, but only once (i.e. first match). The String class provides only replace(), which replaces ALL instances of the substring; there is a replaceFirst() method but it only takes regexp instead of a regular string. I have two concerns with using regex:

1) my substring is dynamic, so might contain weird characters that mean something else in regex, and I don't want deal with character escaping.

2) this replacement happens very often, and I'm not sure whether using regex will impact performance. I can't compile the regex beforehand since the regex itself is dynamic!

I must be missing something here since this seems to me is a very basic thing... Is there a replaceFirst method taking regular string somewhere else in the java franework?

like image 758
polyglot Avatar asked Oct 24 '09 04:10

polyglot


People also ask

How do you replace only one occurrence of a string in Java?

To replace the first occurrence of a character in Java, use the replaceFirst() method.

How do you replace a specific string in Java?

Java String replace() Method The replace() method searches a string for a specified character, and returns a new string where the specified character(s) are replaced.

How do you replace a word in a string in Java without using replace method?

To replace a character in a String, without using the replace() method, try the below logic. Let's say the following is our string. int pos = 7; char rep = 'p'; String res = str. substring(0, pos) + rep + str.


1 Answers

You should use already tested and well documented libraries in favor of writing your own code!

StringUtils.replaceOnce("aba", "a", "")    = "ba" 

The StringUtils class is from Apache Commons Lang3 package and can be imported in Maven like this:

<dependency>     <groupId>org.apache.commons</groupId>     <artifactId>commons-lang3</artifactId>     <version>3.8.1</version> </dependency> 
like image 150
Daniel Gerber Avatar answered Sep 19 '22 16:09

Daniel Gerber