Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can regex do basic arithmetic?

Tags:

regex

math

pcre

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)

like image 340
SoniEx2 Avatar asked Feb 07 '23 15:02

SoniEx2


1 Answers

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

Addition

Replace $ or ^ with a string of the length to add.

'XXXXX' -replace '^', 'XXX' = XXXXXXXX  # 5 + 3

Subtraction

Replace .{n}$ with n being the number to subtract by nothing.

'XXXXX' -replace '.{3}$', '' = XX       # 5 - 3

Multiplication

Replace . with a string of the length to multiply.

'XX' -replace '.', 'XXX' = XXXXXX       # 2 * 3

Division

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

like image 186
Joey Avatar answered Mar 06 '23 06:03

Joey