0

I want to remove everything after last hyphen branch:resource-fix-c95e12f

I have tried with following command :

replaceAll(".*[^/]*$","");

I want the expected result as branch:resource-fix

marglet
  • 21
  • 5
  • Does expected solution *requires* regex? If so you can use `replaceAll("(.*)-[^-]*$","$1")`. `$x` in replacement part represents content of group x, here group 1: `(.*)`. – Pshemo Aug 07 '19 at 07:23

4 Answers4

4

Instead of regex, could you use

String::lastIndexOf?

str.substring(0,str.lastIndexOf(‘-‘))

achAmháin
  • 4,176
  • 4
  • 17
  • 40
1

You can use this regex:

-[^-]+$

Example: https://regex101.com/r/dHSNNN/1

Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125
  • ***On side note:-*** this will not replace `hello-`, you may want to review the quantifier used – Code Maniac Aug 07 '19 at 06:54
  • @CodeManiac, should it? I believe it is unclear, moreover, here we provide not a complete solution but a guidance, if OP needs, he/she can adjust the proposed solution. – Kirill Polishchuk Aug 07 '19 at 06:56
1

You can use the following pattern

-[^-]*$

enter image description here

Demo

Code Maniac
  • 37,143
  • 5
  • 39
  • 60
1

This expression might simply work:

-[^-]*$

Test

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "-[^-]*$";
final String string = "branch:resource-fix-c95e12f";
final String subst = "";

final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);

final String result = matcher.replaceAll(subst);

System.out.println(result);

Another option would be, ^(.*)-.*$ replaced with \\1.

Demo 2


The expression is explained on the top right panel of regex101.com, if you wish to explore/simplify/modify it, and in this link, you can watch how it would match against some sample inputs, if you like.

Emma
  • 27,428
  • 11
  • 44
  • 69