Delete chunk from a string with replaceAll

Asked

Viewed 336 times

2

I have a string, example:

&texto-outroTexto=09213sdadwqWDQS

Where "09213sdadwqWDQS" would be any text and "&texto-outroTexto=" would be a fixed text.

I wanted to do the Regex of that string. I did it that way but it didn’t work:

texto.replaceAll("&texto-outroTexto=[A-Za-z0-9]","");

As I would?

  • 1

    "did not work" is half vague. Do you want to remove which passage? The first part (the fixed text) or the second (the "any text")? What should be the final string?

  • I wanted to remove the whole section

  • &text-otherText=09213sdadwqWDQS I wanted to remove this whole chunk from the rest of the String

1 answer

4


You almost got it right.

To remove the whole section, you must use a regex that has the fixed part, followed by the "any text" part, but using a quantifier, as * or +:

String s = texto.replaceAll("&texto-outroTexto=[A-Za-z0-9]*", "");

Look at the *. It means "zero or more repetitions" of whatever you have before. As what comes before is [A-Za-z0-9] (letters or numbers), that means you want zero or more occurrences of any of these characters.

Without the *, a regex replaced only one occurrence of the character. And don’t forget to assign the result of replaceAll in a variable, because this method returns another String (to String original is not changed).

You can also change the quantifier to + (one or more occurrences), will depend on your use cases.

Or, if you know the amount of characters, you can also use {}, in 3 different ways:

  • [A-Za-z0-9]{2,8}: not less than 2, not more than 8 characters
  • [A-Za-z0-9]{2,}: at least 2 characters, no maximum limit
  • [A-Za-z0-9]{8}: exactly 8 characters

Use whatever fits best for your case.

For more details on the quantifiers, see this tutorial.

  • 2

    HAHA! Thank you very much hkotsubo! It worked!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.