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

Is there a way to replace the last N letters of words longer than X digits?

Does anyone know how can I replace the last N letters of words longer than X digits?
I’m using this code

text = re.sub("[A-ZÀ-ÖØ-Ýà-öø-ÿa-z][A-ZÀ-ÖØ-Ýà-öø-ÿa-z]{7,}", "[\g<0>]", text)

This is an example output string of what I’m getting now.

253.  Ficam [revogadas] a Lei nº 1.711, de 28 de outubro de 1952, e [respectiva] [legislação] [complementar], bem como as demais [disposições] em [contrário].

It puts a [] around words that are greater than 7 letters.
However, I just need to wrap the last letter, not the whole word. Does anyone know how to achieve this?
This is my expected output:

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

253.  Ficam revogada[s] a Lei nº 1.711, de 28 de outubro de 1952, e respectiv[a] legislaçã[o] complement[r], bem como as demais disposiçõe[s] em contrári[o].

>Solution :

You may use this regex for search:

(\b\w{6,})(\w)

And use: \1[\2] for replacement.

RegEx Demo

Code:

import re
text = '253.  Ficam revogadas a Lei nº 1.711, de 28 de outubro de 1952, e respectiva legislação complementar, bem como as demais disposições em contrário.'

print (re.sub(r'(\b\w{6,})(\w)', r'\1[\2]', text))

Output:

253. Ficam revogada[s] a Lei nº 1.711, de 28 de outubr[o] de 1952, e respectiv[a] legislaçã[o] complementa[r], bem como as demais disposiçõe[s] em contrári[o].

RegEx Details:

  • (\b\w{6,}): Match word boundary followed by 6+ word characters in capture group #1
  • (\w): Match last word in capture group #2
  • \1[\2]: Replacement to put first capture group followed by last word wrapped in [.]
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