简体   繁体   中英

Extract number and text from string with RegExp exec Javascript

I'm trying to extract a number and text from strings like those: 171Toberin, [171]Toberin or [171] Toberin.

I have this RegExp /(?<code>\d+)(?<name>\w+)/u , and this RegExp only works with 171Toberin.

You can use the below regex to remove all non alphanumeric characters.

 let string = '171Toberin, [171]Toberin or [171]'; console.log(string.replace(/[^a-zA-Z0-9]/g, ''));

Or use the below to extract the alphanumeric characters from string.

 let string = '171Toberin, [171]Toberin or [171]'; console.log(string.match(/[a-zA-Z0-9]+/g));

Or if you want to extract numbers and strings in separate array then use the below one.

 let string = '171Toberin, [171]Toberin or [171]'; console.log(string.match(/[0-9]+/g)); console.log(string.match(/[a-zA-Z]+/g));

Please try with this: (?<code>\d+)[^\d\w]*(?<name>\w+)/ug

It works with the entire sentence: 171Toberin, [171]Toberin or [171] Toberin.

Returning 3 matches. You can try it at https://regex101.com/

With [^\d\w]* you omit possible numbers and words in between. With g flag you return all matches.

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