0

I would like to match one digit and later match it again (it can be done using backreferences) but decremented by one.

Here is an example regex:

"([0-9])abc\\1"

Is it somehow possible to decrement by one value from the backreference - \\1 ?

Edit I use boost regex.

Alexander Nied
  • 12,804
  • 4
  • 25
  • 45
Irbis
  • 1,432
  • 1
  • 13
  • 39
  • 5
    No, it is not possible with plain regex. – Wiktor Stribiżew Apr 10 '19 at 18:46
  • 1
    To clarify @WiktorStribiżew's comment: Regex contains no logic to implement arithmetic functions. You can accomplish this with a higher-level language that implements a regex engine, but you haven't provided the language nor the code you've tried thus far. – esqew Apr 10 '19 at 18:47
  • 1
    usually when you're doing things like this, you're not trying to find "a number and then later on a number that's one less", you're trying to find "a thing", so describe that thing, and then it's entirely likely that the real solution is "don't use a regex at all, but use .. " – Mike 'Pomax' Kamermans Apr 10 '19 at 18:47

2 Answers2

1

People are going to hate me for this, but I found it to be an interesting exercise. While regex can't do arithmetic, you can use conditional groups to effectively build a library that maps each numeral to its -1 value.

^(1)?(2)?(3)?(4)?(5)?(6)?(7)?(8)?(9)?abc(?(1)0)(?(2)1)(?(3)2)(?(4)3)(?(5)4)(?(6)5)(?(7)6)(?(8)7)(?(9)8)$

https://regex101.com/r/47XDtD/1

The other answer posted here is a lot more straightforward and computationally efficient, but the conditional groups will allow for more flexibility in case your real data is more complex (for example, if you need to match the decremented number multiple times).

CAustin
  • 4,525
  • 13
  • 25
0

Ugly but works:

1abc0|2abc1|3abc2|4abc3|5abc4|6abc5|7abc6|8abc7|9abc8

Just substitute abc with your string.

Just gets all combinations of numbers.

Gymhgy
  • 338
  • 4
  • 11