Stanley Clark
Stanley Clark

Reputation: 71

Regex for matching only first of two same characters in a string

I have these two strings: "1-2" and "1--2".

I would like to have a regex that would match only the first occurrence of the hyphen in both strings, such that the split would then be: [1,2] and [1,-2]. How would I achieve this, since I have been wracking my brain for too long on this now?

EDIT: The two strings can also occur in the same string such that: "1-2-1--2". Therefore a single regular expression covering both cases would be in order.

Upvotes: 2

Views: 255

Answers (3)

Mohammad Altaleb
Mohammad Altaleb

Reputation: 51

I think you're looking for something like this:

(-?[0-9]+)-(-?[0-9]+)

where the first and the second group could have a negative sign

UPDATE: based on your edit, this implementation would do the job:

var str = '-1--2-2--34-1';
var regex = /(-?\d+)-?/g;
var matches = [];
while((match = regex.exec(str))) {
    matches.push(match[1]);
}
console.log(matches);

I prefer using split, but it's fine if you only want to use RegEx.

Upvotes: 1

anubhava
anubhava

Reputation: 785058

You can use this split with a word boundary before -:

let s='1-2-1--2'
let arr = s.split(/\b-/)

console.log(arr)
//=> [1, 2, 1, -2)

Upvotes: 4

Chayim Friedman
Chayim Friedman

Reputation: 70910

You can use simple split(), but with replacement. For example,

var str = '1-2-1--2';

var numArr = str.replace(/--/g, '-~') // The tilde (~) have no mean, this is a charceter for mark a negative number
  .split('-')
  .map(function(n) { return Number(n.replace('~', '-')); });

console.log(numArr);

Upvotes: 1

Related Questions