Home > database >  replaceAll regex to remove last - from the output
replaceAll regex to remove last - from the output

Time:06-17

I was able to achieve some of the output but not the right one. I am using replace all regex and below is the sample code.

final String label = "abcs-xyzed-abc-nyd-request-xyxpt--1-cnaq9";
System.out.println(label.replaceAll(
   "([^-] )-([^-] )-(. )-([^-] )-([^-] )", "$3"));

i want this output:

abc-nyd-request-xyxpt

but getting:

abc-nyd-request-xyxpt-

here is the code https://ideone.com/UKnepg

CodePudding user response:

The following works for your example case

([^-] )-([^-] )-(. [^-])- ([^-] )-([^-] )

https://regex101.com/r/VNtryN/1

We don't want to capture any trailing - while allowing the trailing dashes to have more than a single one which makes it match the double --.

CodePudding user response:

You may use this .replaceFirst solution:

String label = "abcs-xyzed-abc-nyd-request-xyxpt--1-cnaq9";
label.replaceFirst("(?:[^-] -){2}(. )-(?:-[^-] ){2}", "$1");
//=> "abc-nyd-request-xyxpt"

RegEx Demo

RegEx Details:

  • (?:[^-] -){2}: Match 2 repetitions of non-hyphenated string followed by a hyphen
  • (. ): Match 1 of any characters and capture in group #1
  • -: Match a -
  • (?:-[^-] ){2}: Match 2 repetitions of hyphen followed by non-hyphenated string

CodePudding user response:

With your shown samples and attempts, please try following regex. This is going to create 1 capturing group which can be used in replacement. Do replacement like: $1in your function.

^(?:.*?-){2}([^-]*(?:-[^-]*){3})--.*

Here is the Online demo for above regex.

Explanation: Adding detailed explanation for above regex.

^(?:.*?-){2}          ##Matching from starting of value in a non-capturing group where using lazy match to match very near occurrence of - and matching 2 occurrences of it.
([^-]*(?:-[^-]*){3})  ##Creating 1st and only capturing group and matching everything before - followed by - followed by everything just before - and this combination 3 times to get required output.
--.*                  ##Matching -- to all values till last.
  • Related