This is a relatively simple question. Can PCRE (without extended features such as being able to call the host's functions) do basic arithmetic? That is, can I add, subtract, divide and multiply unary non-negative integers using PCRE? If so, how? (note: I can control both the input, the regex and the replacement string)
Yes, you can. By using unary numbers, that is, the number is just the length of the string. This is similar to how regexes can check for prime numbers (Samples in PowerShell for now because most of this is so basic that every engine should be able to do it.)
Replace $
or ^
with a string of the length to add.
'XXXXX' -replace '^', 'XXX' = XXXXXXXX # 5 + 3
Replace .{n}$
with n
being the number to subtract by nothing.
'XXXXX' -replace '.{3}$', '' = XX # 5 - 3
Replace .
with a string of the length to multiply.
'XX' -replace '.', 'XXX' = XXXXXX # 2 * 3
Replace \G.{n}(?=(.{n})*$)
with a string of length 1
; with n
being the number of divide by. The string doesn't change if a replacement isn't possible.
'XXXXXX' -replace '\G.{3}(?=(.{3})*$)', 'X' = XX # 6 / 3
'XXXXXX' -replace '\G.{4}(?=(.{4})*$)', 'X' = XXXXXX # 6 / 4 (!)
That being said, the commenters on the question are correct: You really shouldn't do this if you can help it (curiosity is fine, though).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With