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)
-
4no..you cannot(or should not)..period..– rock321987Jul 3, 2016 at 14:05
-
1The regex alone (that is only a string description) isn't really able to do that, but: 1) in a replacement context it's possible to use functions to do what you want, 2) when implemented, pcre can call functions in the pattern itself (but not sure it can be useful in your case).– Casimir et HippolyteJul 3, 2016 at 14:10
-
1In computer science theory, it's not possible. There are some engines that have extensions that make it possible; but hey, please.. don't think about it.– MarounJul 3, 2016 at 14:12
-
1@Joey at some point, you have to use functionality provided by a programming language..PCRE alone will not be able to do it(till I know)..if you have any suggestion please go ahead– rock321987Jul 3, 2016 at 14:14
-
1@SWLim Just out of sheer curiosity. And it could come in handy for codegolf.– SoniEx2Jul 3, 2016 at 14:52
1 Answer
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).
-
2This is not really the math OP expects this: can I add, subtract, divide and multiply numbers using PCRE. These examples are still string manipulation approaches. Jul 3, 2016 at 14:30
-
1
-
@Joey Any way to make division be floor division? (7/3 = 2, 7/4 = 1, etc)– SoniEx2Jul 3, 2016 at 14:33
-
@SoniEx2: you can use
(?:(.){n})?(?:.{0,n-1}$)?with\1as replacement. Jul 3, 2016 at 14:48 -