Home > Back-end >  Regex, Find any number except for the number preceded by a letter
Regex, Find any number except for the number preceded by a letter

Time:12-13

I want to find all numbers except those preceded by English letter

example one: test123 I don't want 123 to match.

example two: another 123 I want 123 to match.

example three: try other solutions 123 I want 123 to match.

I tried many and no one get the desired result, last one was

let reg = /((?<![a-zA-Z])[0-9]){1,}/g;

but it just ignore this first number I want to ignore all

example : test123 - it ignored 1 but take 23 , the desired result is ignore 123

I tried this regex but did not work as well

let reg = /((?<![a-zA-Z])[0-9]){1,}/g;

and the result must ignore all digits number after English letter

CodePudding user response:

You can use

const reg = /(?<![a-zA-Z\d]|\d\.)\d (?:\.\d )?/g;

See the regex demo. Details:

  • (?<![a-zA-Z\d]|\d\.) - a negative lookbehind that fails the match if there is a letter/digit or a digit followed with a dot immediately to the left of the current location
  • \d (?:\.\d )? - one or more digits followed with an optional sequence of a . and one or more digits.

JavaScript demo:

const text = "test123\ntest 456\ntest123.5\ntest 456.5";
const reg = /(?<![a-zA-Z\d]|\d\.)\d (?:\.\d )?/g;
console.log(text.match(reg)); // => ["456","456.5"]

For environments not supporting ECMAScript 2018 standard:

var text = "test123\ntest 456\ntest123.5\ntest 456.5";
var reg = /([a-zA-Z])?\d (?:\.\d )?/g;
var results = [], m;
while(m = reg.exec(text)) {
  if (m[1] === undefined) {
     results.push(m[0]);
   }
}
console.log(results); // => ["456","456.5"]

  • Related