Neeka
Neeka

Reputation: 69

Regex: get number after and before specific substring

I'm new to regex and trying to get number after substring text and before first non-numeric value. I have:

const str = 'fasdfsdanvczx fdasvczx text 321,fasdgasdf'; str.toLowerCase().match(new RegExp('text (.*)[^0-9]'));

As a result I'm receiving: ["text 321,fasdgasdf", "321,fasdgasd"] but I want only 321.

Thanks in an advance for any help.

Upvotes: 2

Views: 387

Answers (3)

The fourth bird
The fourth bird

Reputation: 163207

You could match the digits only in the first capturing group and use word boundaries \b to prevent text and the digits being part of a larger word.

Note to double escape the backslashes when using the RegExp constructor.

\btext (\d+)\b

Regex demo

const str = 'fasdfsdanvczx fdasvczx text 321,fasdgasdf';
let res = str.toLowerCase().match(new RegExp('\\btext (\\d+)\\b'));
console.log(res[1]);

Upvotes: 3

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520908

You may try splitting twice:

var str = 'fasdfsdanvczx fdasvczx text 321,fasdgasdf';
var num = str.split(/text /)[1].split(/\D/)[0];
console.log(num);

The first spiit leaves us with 321,fasdgasdf, and the second split discards everything from the comma onwards.

Upvotes: 0

Raymond Reddington
Raymond Reddington

Reputation: 1837

Use lookbehind to find number after 'text ':

(?<=text )\d+

Or simply match parts and select second group:

(text )(\d+)

Upvotes: 1

Related Questions