import Foundation
// WARNING: You included a flag that Swift doesn't support: u
// When this flag is set, it makes the pattern and subject strings to be treated as unicode.
// Swift already treats the pattern and subject strings as unicode by default, so including this flag is redundant.
let pattern = ##"""
# 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
"""##
let regex = try! NSRegularExpression(pattern: pattern, options: [.caseInsensitive, .allowCommentsAndWhitespace])
let testString = #"""
vinte cinco
vinte cinco mil
vinte cinco reais
vinte cinco reais e vinte cinco centavos
aaa bbb ccc
dois mil trezentos
dois mil trezentos quarenta cinco
dois milhões trinta um
dois milhões trinta um mil
dois milhões trinta mil
cento vinte três milhões quatrocentos cinquenta seis mil setecentos oitenta nove
"""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let substitutionString = #"e "#
let result = regex.stringByReplacingMatches(in: testString, range: stringRange, withTemplate: substitutionString)
print(result)
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 Swift 5.2, please visit: https://developer.apple.com/documentation/foundation/nsregularexpression