Delete a string with replaceAll

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 this string. I did it that way, but it did not work:

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

How would I do it?

    
asked by anonymous 30.05.2018 / 19:21

1 answer

4

You almost got it right.

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

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

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

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

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

Or, if you know the amount of characters, you can also use {} . For example, if you know you can have 2 to 8 characters, you can use {2,8} instead of * . For more details on quantifiers, see this tutorial .

    
30.05.2018 / 19:31