deeveeABC
deeveeABC

Reputation: 986

Use regex java to replace a string before and after a certain character

My effort: I tried looking at similar questions however I cannot figure out my answer. I also tried using the web (https://www.cheatography.com/davechild/cheat-sheets/regular-expressions/) to figure this out myself, but I just cant get the right answer. Tried using myString.replaceAll("_.+/[^.]*/", "");

I have a string: String myString = "hello_AD123.mp3";

And I want to use regex java in order to REMOVE everything after the underscore (including it) AND stopping before the (.mp3). How would I do this?

So I want the final result to be the following: myString = "hello.mp3";

Upvotes: 1

Views: 11283

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627507

Your regex did not work because it matched something that is missing from your string:

  • _ - an underscore followed with...
  • .+ - one or more any characters other than a line feed
  • / - a literal / symbol
  • [^.]* - zero or more characters other than a dot
  • / - a literal /.

There are no slashes in your input string.

You can use

String myString = "hello_AD123.mp3";
myString = myString.replaceFirst("_.*[.]", ".");
// OR myString = myString.replaceFirst("_[^.]*", "");
System.out.println(myString);

See the IDEONE Java demo

The pattern _[^.]* matches an underscore and then 0+ characters other than a literal dot. In case the string has dots before .mp3, "_.*[.]" matches _ up to the last ., and needs to be replaced with a ..

See the regex Demo 1 and Demo 2.

Details:

  • _ - matches _
  • [^.]* - matches zero or more (due to * quantifier) characters other than (because the negated character class is used, see [^...]) a literal dot (as . inside a character class - [...] - is treated as a literal dot character (full stop, period).

    • OR
  • .*[.] - matches 0 or more characters other than a newline up to the last literal dot (consuming the dot, thus, the replacement pattern should be ".").

The .replaceFirst() is used because we only need to perform a single search and replace operation. When the matching substring is matched, it is replaced with an empty string because the replacement pattern is "".

Upvotes: 4

Related Questions