Skip to content Skip to sidebar Skip to footer

Javascript Positive Lookbehind Alternative

So, js apparantly doesn't support lookbehind. What I want is a regex valid in javascript that could mimic that behavior. Specifically, I have a string that consists of numbers and

Solution 1:

I don't know why you want to match the delimiting hyphen, instead of just matching the whole string and capture the numbers:

input.match(/(-?\d+) *- *(-?\d+)/)

The 2 numbers will be in capturing group 1 and 2.

It is possible to write a regex which works for sanitized input (no space, and guaranteed to be valid as shown in the question) by using \b to check that - is preceded by a word character:

\b-

Since the only word characters in the sanitized string is 0-9, we are effectively checking that - is preceded by a digit.

Solution 2:

(\d+.*?)(?:\s+(-)\s+)(.*?\d+)

You probably want this though i dont know why there is a diff between expected output of 2nd and 4th.Probably its a typo.You can try this replace by $1$2$3.See demo.

http://regex101.com/r/yR3mM3/26

var re = /(\d+.*?)(?:\s+(-)\s+)(.*?\d+)/gmi;
var str = '12 - 23\n12 - -23\n-12 - 23\n-12 - -23';
var subst = '$1$2$3';

var result = str.replace(re, subst);

Post a Comment for "Javascript Positive Lookbehind Alternative"