So we can do this entirely in regular expressions. We will use this to replace digits by their corresponding successors. We add a little 'lookup' to the end of our string (also delimited with a unique character that does not occur in your string for simplicity I used #). Since we will be replacing one digit per number at a time (from right to left), we will just add that marking character after every full number. I used this test string: $str = '0 1 2 3 4 5 6 7 8 9 10 11 12 13 19 20 29 99 100 139' įirst of all, let's mark all digits we want to increment by appending a marker character (I use ~, but you should probably use some crazy Unicode character or ASCII character sequence that definitely will not occur in your target string. Here is my demo implementation using PHP. But if you prepare the string first, there is a single replacement that can be looped. So first of all, as the others mentioned, it is not possible in a single replacement, even if you loop it (because how would you insert the corresponding increment to a single digit). In case you do not have the time or cannot be bothered to read through the whole explanation, here is the code that does it: $str = '0 1 2 3 4 5 6 7 8 9 10 11 12 13 19 20 29 99 100 139' Wow, turns out it is possible (albeit ugly)! Thus "09~" becomes "19~" then "10~" as the regex engine parses the number. Replace with the next digit in the lookup table. So this means match all digits that are followed by 9s until the '~' mark then go to the lookup table and find the digit following this number. (?=) is positive lookahead, \1 is match group #1. Select the "0" digit in front of all numbers that do not need rounding and discard it. The individual pieces of the next regex can be described seperately, they are joined via pipes to reduce substitution count: s/\b0(?!9*~)/$2/g The 01234567890 block is for incrementing. The first 0 is in case rounding 9 to 10 is needed. My implementation environment is solaris, full example: echo "0 1 2 3 7 8 9 10 19 99 109 199 9 1909" | My solution happens to be two substitutions so I'll post it. This question's topic amused me for one particular implementation I did earlier.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |