简体   繁体   中英

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:

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].

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 [.]

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