简体   繁体   中英

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.

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]);

Use lookbehind to find number after 'text ':

(?<=text )\d+

Or simply match parts and select second group:

(text )(\d+)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM