dubis
dubis

Reputation: 378

How to exclude first and second minus character from the right?

I've this list above I'm working a REGEX on https://regex101.com/

BETA - Asia-926-5.6.6
BETA - Asia-926-5.5.7
BETA - AU-843-5.6.6
BETA - AU-843-5.5.7
BETA - East-Europe-500-5.6.6
BETA - East-Europe-500-5.5.7

I found this REGEX [^0-9,.] to exclude all digits and point but I don't how to exclude the first and second minus character from the right for get something like this :

BETA - Asia
BETA - Asia
BETA - AU
BETA - AU
BETA - East-Europe
BETA - East-Europe

Upvotes: 0

Views: 130

Answers (3)

Peter Thoeny
Peter Thoeny

Reputation: 7616

Here is a simple regex to remove a dash, followed by number, and all remaining characters:

var strings = [
  'BETA - Asia-926-5.6.6',
  'BETA - Asia-926-5.5.7',
  'BETA - AU-843-5.6.6',
  'BETA - AU-843-5.5.7',
  'BETA - East-Europe-500-5.6.6',
  'BETA - East-Europe-500-5.5.7'
];
var regex = /\-[0-9].*$/;
strings.forEach(function(str) {
  var result = str.replace(regex, '')
  console.log(str + ' ==> ' + result);
});

Output:

BETA - Asia-926-5.6.6 ==> BETA - Asia
BETA - Asia-926-5.5.7 ==> BETA - Asia
BETA - AU-843-5.6.6 ==> BETA - AU
BETA - AU-843-5.5.7 ==> BETA - AU
BETA - East-Europe-500-5.6.6 ==> BETA - East-Europe
BETA - East-Europe-500-5.5.7 ==> BETA - East-Europe

Explanation of regex:

  • \- - a literal dash
  • [0-9] - a digit
  • .*$ - everything to end

The replacement part is empty, hence it will remove the match.

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626794

You can match all text beginning with the last but one hyphen using

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

See the regex demo

Details

  • (?:-[^-]*){2} - two occurrences ({2}) of
    • - - a hyphen
    • [^-]* - 0 or more chars other than -
  • $ - end of string.

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163287

You could match the last 2 hyphens and the pattern for the digits, and replace the match with an empty string.

-\d+-\d+(?:\.\d+)+$
  • -\d+- Match -, 1+ digits and -
  • \d+ Match 1+ digits
  • (?:\.\d+)+ Match 1+ times a dot and 1+ digits
  • $ End of string.

Regex demo

Output

BETA - Asia
BETA - Asia
BETA - AU
BETA - AU
BETA - East-Europe
BETA - East-Europe

Upvotes: 1

Related Questions