Regex to increase or decrease last digit in line by one.
-
So I want to know if there is a regex to increase or decrease the value of the last digit in a line by one.
Example:Reg1ex234 >>>> Reg1ex235
I’ve seen several examples to change ALL the digits in a line, but not the last one. Is this possible by regex only?
-
@guy038 I saw your reply https://community.notepad-plus-plus.org/topic/14884/regex-to-change-numbers-to-a-value-1-step-lower/2
Is this possible only for the last digit in the line via regex? Thank you!
-
If your intent is to only ever affect the last digit, then yes, perfectly possible. But…most people would expect a change of this sort to transform
2019into2020(note that TWO digits changed!) and this is not a reasonable expectation from regex replacement.However, if that’s acceptable, then a way to change the only the last digit appearing on a line to the next digit lower is to search for
(?-s)^(.+)(?:(0)|(1)|(2)|(3)|(4)|(5)|(6)|(7)|(8)|(9))and replace with\1(?{2}9)(?{3}0)(?{4}1)(?{5}2)(?{6}3)(?{7}4)(?{8}5)(?{9}6)(?{10}7)(?{11}8)That borrows heavily from the other post you linked to. :-)
-
Thank you very much @Alan-Kilborn . It will be enough to resolve my current problem :).
-
@Alan-Kilborn Hello again, could you help me with the regex to do this to the first number in every line instead of last?
-
@Reggy-guy said:
the regex to do this to the first number in every line instead of last
Deceptively simple, I think.
Just add a
?after the+in the earlier search expression. -
I should add that it works for this reason:
.+ :
.+matches (one or more characters) as much as it can before moving on. Also known as the “maximum munch”. So given the pattern.+\dand the string-to-test asabc123def345the.+part would matchabc123def34because the ending5would satisfy the\din the pattern..+? :
.+?matches (one or more characters) as little as possible before moving on. Also known as the “minimum munch”. With the pattern.+?\dand the same string-to-test, the.+?part would matchabcbecause the following1would match the\d.