SoniEx2
SoniEx2

Reputation: 2044

Can regex do basic arithmetic?

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)

Upvotes: 5

Views: 4780

Answers (1)

Joey
Joey

Reputation: 354694

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

Upvotes: 8

Related Questions