How to do a regular expression to remove only the hyphen without removing the hyphenated arrow

3

I have the following expression:

  

00000-001-> 22222-222

I would like it to look like this:

  

00000001- > 22222222

I've tried various ways on this site , but I'm not getting it.

    
asked by anonymous 16.03.2016 / 15:57

2 answers

6

You can use negative lookahead "(?!) , deny a coming pattern the front of another pattern. Example in php:

preg_replace('/-(?!>)/', '', '00000-001->22222-222');

Or in javascript:

var result = '00000-001->22222-222'.replace(/-(?!>)/g, '');
document.write(result);

The /-(?!>)/ pattern means " - that is not directly followed by > " and will return "00000001->22222222" .

    
16.03.2016 / 16:09
4

You can do this:

var str = '00000-001->22222-222';
var limpa = str.replace(/\-/g, function(match, pos) {
    return str.slice(pos + 1, pos + 2).match(/\d/) ? '' : '-';
});
console.log(limpa); // dá 00000001->22222222

jsFiddle: link

or as BrunoRB suggested :

var str = '00000-001->22222-222';
var limpa = str.replace(/\-([^>])/g, '$1');
console.log(limpa); // dá 00000001->22222222

jsFiddle: link

    
16.03.2016 / 16:09