# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"""
# Definição de ordens
(?(DEFINE)(?P<unidades> um|dois|tr[eê]s|quatro|cinco|meia|se(?:is|te)|oito|nove ))
(?(DEFINE)(?P<dezenas_dez> d(?:ez(?:e(?:nove|sse(?:is|te))|oito)?|oze)|onze|treze|catorze|quinze ))
(?(DEFINE)(?P<dezenas_exceto_dez> vinte|trinta|(?:quar|cinqu|se(?:ss|t)|oit|nov)enta ))
(?(DEFINE)(?P<dezenas> (?P>dezenas_dez)|(?P>dezenas_exceto_dez) ))
(?(DEFINE)(?P<dezenas_ou_unidades> (?P>dezenas)|(?P>unidades) ))
(?(DEFINE)(?P<centenas> ce(?:m|ntos?)|(?:qu(?:atroc|inh)|(?:du|tre|se(?:is|te)|oito|nove)[cz])entos? ))
(?(DEFINE)(?P<mil> mil ))
(?(DEFINE)(?P<milhoes> (?:(?:[mb]|tr)i|qu(?:atri|inqua))lh(?:[aã]o|[oõ]es) ))
(?(DEFINE)(?P<s> [ ]+ ))
(?(DEFINE)(?P<e> e(?P>s) ))
#Regras
\b(?:
#1. Entre dezenas>=20 e unidades
(?P>dezenas_exceto_dez)(?P>s)(?=(?P>unidades)\b)
|
#2. Entre centenas e dezenas ou unidades
(?P>centenas)(?P>s)(?=(?P>dezenas_ou_unidades)\b)
|
#3-4. Entre milhares...
(?P>mil)(?P>s)(?=
(?:
#3. ... e dezenas ou unidades
(?P>dezenas_ou_unidades)
|
#4. ... e centenas, somente se não houver dezenas ou unidades
(?P>centenas)(?!(?P>s)(?P>e)?(?P>dezenas_ou_unidades)\b)
)
\b
)
|
#5. Entre milhões e dezenas ou unidades (que não sejam unidades ou dezenas de milhões ou unidades ou dezenas de milhares)
(?P>milhoes)(?P>s)(?=
(?P>dezenas_ou_unidades)(?!(?P>s)(?P>e)?(?:(?P>unidades)(?P>s)(?P>e)?)?(?:(?P>milhoes)|(?P>mil))\b)\b
)
)
\b
#Reset
\K
"""
test_str = ("vinte cinco\n"
"vinte cinco mil\n"
"vinte cinco reais\n"
"vinte cinco reais e vinte cinco centavos\n"
"aaa bbb ccc\n"
"dois mil trezentos\n"
"dois mil trezentos quarenta cinco\n"
"dois milhões trinta um\n"
"dois milhões trinta um mil\n"
"dois milhões trinta mil\n"
"cento vinte três milhões quatrocentos cinquenta seis mil setecentos oitenta nove")
subst = "e "
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.IGNORECASE | re.VERBOSE | re.UNICODE)
if result:
print (result)
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Python, please visit: https://docs.python.org/3/library/re.html