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

Asked

Viewed 1,146 times

3

I have the following expression:

00000-001->22222-222

I wish she’d stay like this:

00000001->22222222

I’ve tried so many ways on this website, but I’m not getting it.

  • PHP or Javascript? :)

2 answers

6


You can use Negative Lookahead "(?!)", deny a pattern that comes in 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 /-(?!>)/ that is to say "- which are not directly followed by >" and will return you "00000001->22222222".

  • I just noticed that the question has PHP tag and Javascript (!)... +1 for the answer with PHP :P

  • Perfect guy, thanks a lot!

4

You can do it like 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: https://jsfiddle.net/0jj507w1/1

or like Brunorb suggested:

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

jsFiddle: https://jsfiddle.net/0jj507w1/2

  • Sergio is wrong because his regex will consider the element that comes in front of - as part of regex and end up removing a "0" from the string, note how the input has 7 zeros and the output has 6. You can fix it using group capture, something like .replace(/\-([^>])/g, '$1');

  • 1

    @Brunorb you’re right, thank you. corrected.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.