Home > Net >  regex to replace a string using replaceAll() or any other method
regex to replace a string using replaceAll() or any other method

Time:10-08

I was trying to replace/remove any string between - <branch prefix> /

Example:

String name = Application-2.0.2-bug/TEST-1.0.0.zip

expected output :

Application-2.0.2-TEST-1.0.0.zip

I tried the below regex, but it's not working accurate.

String FILENAME = Application-2.0.2-bug/TEST-1.0.0.zip

println(FILENAME.replaceAll(". /", ""))

CodePudding user response:

Please, try this one:

String FILENAME = "Application-2.0.2-**bug/**TEST-1.0.0.zip";
System.out.println(FILENAME.replaceAll("\\*\\*(.*)\\*\\*", ""));
       

CodePudding user response:

You can use

FILENAME.replaceAll("-[^-/] /", "-")

See the regex demo. Details:

  • - - a hyphen
  • [^-/] - any one or more chars other than - and /
  • / - a / char.

See the online Groovy demo:

String FILENAME = 'Application-2.0.2-bug/TEST-1.0.0.zip'
println(FILENAME.replaceAll("-[^-/] /", "-"))
// => Application-2.0.2-TEST-1.0.0.zip
  • Related