Quote:
Originally Posted by Toxaris
What would the added value of a RegEx function?
|
If you really want an answer, I recommend this link:
https://manual.calibre-ebook.com/function_mode.html
In addition, as an example I bring two codes to switch arabic numbers to romans, and viceversa.
Code:
#Searching: (?)(\d+)(?)
def num_roman(input):
ints = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
nums = ('M', 'CM', 'D', 'CD','C', 'XC','L','XL','X','IX','V','IV','I')
result = ""
input=int(input)
for i in range(len(ints)):
count = input//ints[i]
result += nums[i] * count
input -= ints[i] * count
return result
def replace(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs):
return match.group(1)+str(num_roman(match.group(2)))+match.group(3)
Code:
#Searching: (?)(.+?)(?)
numeral_map = zip(
(1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1),
('M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I')
)
def arabic_num(n):
n = unicode(n).upper()
i = result = 0
for integer, numeral in numeral_map:
while n[i:i + len(numeral)] == numeral:
result += integer
i += len(numeral)
return result
def replace(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs):
return match.group(1)+str(arabic_num(match.group(2)))+match.group(3)