itgeek
itgeek

Reputation: 589

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

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(".+/", ""))

Upvotes: 1

Views: 2610

Answers (3)

Kaus2b
Kaus2b

Reputation: 845

I find that using groovy closures for string replaces are most intuitive and easy to understand.

def str = "Application-2.0.2-bug/TEST-1.0.0.zip"

def newStr = str.replaceAll(/(.*-)(.*\/)(.*)/){all,group1,group2,group3 -> 
    println all
    println group1
    println group2
    println group3
    "${group1}${group3}" //this is the return value of the closure
}

println newStr 

This is the output

Application-2.0.2-bug/TEST-1.0.0.zip
Application-2.0.2-
bug/
TEST-1.0.0.zip
Application-2.0.2-TEST-1.0.0.zip

Explanation:

If you notice in the regex that char groups are all in parentheses (). This denotes the groups in the input string. These groups can then be used in an easy way in a closure.

  • all - first variable will always be full string
  • group1 - (.*-) to indicate all chars ending with -
  • group2 - (.*\/) to indicate all chars ending with / (escaped with \).
  • group3 - (.*) all remaining chars

Now for your requirement all you need is to eliminate group2 and return a concatenation of group1 and group3.

By using this technique you can use the closure pretty powerfully, just make sure that the number of arguments in the closure (in this case 4) equal 1 more than the number of groups in the regex since the first one is always full input string. You can dynamically have any number of groups depending on your scenario

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

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

Upvotes: 2

toootooo
toootooo

Reputation: 196

Please, try this one:

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

Upvotes: 1

Related Questions