Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regular expression for highlighting numbers between words

Site users enter numbers in different ways, example:

from 8 000 packs
432534534
from 344454 packs
45054 packs
04 555
434654
54 564 packs

I am looking for a regular expression with which I could highlight words before digits (if there are any), digits in any format and words after (if there are any). It is advisable to exclude spaces.

Now I have such a design, but it does not work correctly.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(^[0-9|a-zA-Z].*?)\s([0-9].*?)\s([a-zA-Z]*$)

The main purpose of this is to put the strings in order, bring them to the same form, format them in PHP digit format, etc.

As a result, I need to get the text before the digits, the digits themselves and the text after them into the variables separately.

$before = 'from';
$num    = '8000';
$after  = 'packs';

Thank you for any help in this matter)

>Solution :

I corrected your regex and added groups, the regex looks like this:

^(?<before>[a-zA-Z]+)?\s?(?<number>[0-9].*?)\s?(?<after>[a-zA-Z]+)?$`

Test regex here: https://regex101.com/r/QLEC9g/2

By using groups you can easily separate the words and numbers, and handle them any way you want.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading