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

RegExp: Match first 3 char words

/[\w|A-Z]{1,3}[a-z]/g
but I want to match only the first 3 char of words.
For example:

I WANt THE FIRst 3 CHAr OF WORds ONLy.

It’s for a rapid lector: only uppercase the begining of any words.

The best could be: (First 3 char)(Rest of the word or space)

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

https://regex101.com/r/PCi8Dn/2

Thank you !

>Solution :

Original answer

Use positive lookahead ((?=[pattern]) to match without including in the match.

[A-Z]{1,3}(?=[a-z])

appears to do what you want (if I’ve understood your spec correctly).

You can see it in action here.

New answer following clarification on spec

I think this does what you want:

(\S{1,3})(\S*[\s\.]+)

The breakdown is:

  • 1st capturing group: (\S{1,3})

Matches a maximum of 3 non-space characters (\S used instead of \w because I think you want to match characters with diacritics like à and punctuation in the middle of words like '.

  • 2nd capturing group: (\S*[\s\.]+)

Matches zero or more non-space characters (the remaining characters in each word) followed by one or more delimiter characters (space or period). I included period as a delimiter to match the last word. You might want to adjust that part depending on your exact needs.

See it in action here.

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