Is it possible to increment numbers using regex substitution?
This question's topic amused me for one particular implementation I did earlier. My solution happens to be two substitutions so I'll post it.
My implementation environment is solaris, full example:
echo "0 1 2 3 7 8 9 10 19 99 109 199 909 999 1099 1909" |
perl -pe 's/\b([0-9]+)\b/0$1~01234567890/g' |
perl -pe 's/\b0(?!9*~)|([0-9])(?=9*~[0-9]*?\1([0-9]))|~[0-9]*/$2/g'
1 2 3 4 8 9 10 11 20 100 110 200 910 1000 1100 1910
Pulling it apart for explanation:
s/\b([0-9]+)\b/0$1~01234567890/g
For each number (#) replace it with 0#~01234567890. The first 0 is in case rounding 9 to 10 is needed. The 01234567890 block is for incrementing. The example text for "9 10" is:
09~01234567890 010~01234567890
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
Select the "0" digit in front of all numbers that do not need rounding and discard it.
s/([0-9])(?=9*~[0-9]*?\1([0-9]))/$2/g
(?=) is positive lookahead, \1 is match group #1. 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. Replace with the next digit in the lookup table. Thus "09~" becomes "19~" then "10~" as the regex engine parses the number.
s/~[0-9]*/$2/g
This regex deletes the ~ lookup table.
Increment a number in a string in with regex
How about:
'url1'.replace(/\d+$/, function(n){ return ++n }); // "url2"
'url54'.replace(/\d+$/, function(n){ return ++n }); // "url55"
There we search for a number at the end of the string, cast it to Number
, increment it by 1, and place it back in the string. I think that's the same algo you worded in your question even.
Reference:
String.prototype.replace
- can take a regex
Incrementing a number in a string using sub
The point is that the backreference is only evaluated during a match operation, and you cannot pass it to any function before that.
When you write as.numeric("\\1")
the as.numeric
function accepts a \1
string (a backslash and a 1
char). Thus, the result is expected, NA
.
This happens because there is no built-in backreference interpolation in R.
You may use a gsubfn
package:
> library(gsubfn)
> s <- "x is 5"
> gsubfn("\\d+", function(x) as.numeric(x) + 1, s)
[1] "x is 6"
increment a number at the end of a string using regex Python
You need to make use of a replacement callback:
# coding=utf8
import re
# Regex to find "-FT{digits}{end of line}
regex = r"(?<=-FT)(\d+)$"
# Increment the digit by one and maintain left pad zeros
def subst(m):
return format(int(m.group(1))+1, '0'+str(len(m.group(1))))
# Test your data
print (re.sub(regex, subst, "CHB-16236-FT-FT005", 0, re.MULTILINE))
print (re.sub(regex, subst, "CHB-16236-FT-FT009", 0, re.MULTILINE))
print (re.sub(regex, subst, "CHB-16236-FT-FT045", 0, re.MULTILINE))
print (re.sub(regex, subst, "CHB-16236-FT-FT145", 0, re.MULTILINE))
print (re.sub(regex, subst, "CHB-16236-FT-FT999", 0, re.MULTILINE))
print (re.sub(regex, subst, "CHB-16236-FT-FT0999", 0, re.MULTILINE))
print (re.sub(regex, subst, "CHB-16236-FT-FT2009", 0, re.MULTILINE))
print (re.sub(regex, subst, "CHB-16236-FT-FT09998", 0, re.MULTILINE))
Results:
CHB-16236-FT-FT006
CHB-16236-FT-FT010
CHB-16236-FT-FT046
CHB-16236-FT-FT146
CHB-16236-FT-FT1000
CHB-16236-FT-FT1000
CHB-16236-FT-FT2010
CHB-16236-FT-FT09999
How can I increment a number matched via regex?
from: Use RegExp to match a parenthetical number then increment it
The replace method can take a function as its second argument. It gets the match (including submatches) and returns the replacement string. Others have already mentioned that the parentheses need to be escaped.
"Item Name (4)".replace(/\((\d+)\)/, function(fullMatch, n) {
return "(" + (Number(n) + 1) + ")";
});
So,
*edit:
this should work
"product[0][0][3][title]".replace(/(^product\[\d+\]\[\d+\]\[)(\d+)(\]\[.+\])/, function(fullMatch, n, a, o) {
return n + (Number(a) + 1) + o;
});
Increment the number part of a String but keeping the character part in Java
You can use this code by stripping all digits first and then stripping all non-digits:
String original = "FR000009";
String repl = String.format("%s%0" + (original.length() - 2) + "d",
original.replaceFirst("\\d+", ""),
(Integer.valueOf(original.replaceFirst("\\D+", "")) + 1));
//=> "FR000010"
Here:
replaceFirst("\\d+", "")
: removes all digits from input, giving usFR
replaceFirst("\\D+", "")
: removes all non-digits from input, giving us000009
Note that if there are always only 2 letters at the start and remaining are digits then you won't even need a regex code, just use substring
:
String repl = String.format("%s%0" + (original.length() - 2) + "d",
original.substring(0, 2),
(Integer.valueOf(original.substring(2)) + 1));
Increment number found with JavaScript regex after a specific string
Use match
parameter
var str = "m 0.05291667,1.7345817 h 0.16018 V 0.05291667 H 1.4943367 v 0.56054601 l -0.16015,0.16017899 0.16015,0.16012501 V 1.4943397 H 0.69354668 V 1.2541247 H 1.2540967 V 1.0138577 L 1.0939467,0.90175268 H 0.69354668 v -0.240215 H 1.0939467 l 0.16015,-0.128138 V 0.29313166 H 0.45330668 V 1.7345817 H 1.6544867"
str = str.replace(/(?<=H )(.*?)(?= )/g, function(match, i, original) { return parseFloat(match) + 2});
console.log(str)
Increment numbers in a string by one
You may try using re.sub
here with a callback function:
an_str = r"""Excel file name: {0}
No.of Iterations: {1}
Cp = {2}
CpK = {3}
There are {4}ppm values below the lower tolerance limit
There are {5}ppm values above the upper tolerance limit
"""
an_str_out = re.sub(r'\{(\d+)\}', lambda m: '{' + str(int(m.group(1)) + 1) + '}', an_str)
print(an_str_out)
This prints:
Excel file name: {1}
No.of Iterations: {2}
Cp = {3}
CpK = {4}
There are {5}ppm values below the lower tolerance limit
There are {6}ppm values above the upper tolerance limit
The idea here is to match every occurrence of {num}
using the pattern \{(\d+)\}
, which capture the number in the first capture group. Then, we pass this match to a lambda callback function, which casts to integer, increments, and then casts back to text for a replacement.
Python regex: How to increase only one number in string?
Ì suggest first extracting the first number and then increment all occurrences of this number when it is not enclosed with other digits with re.sub
:
import re
a1 = 'images1subimages1/folder100/hello1.png'
num0_m = re.search(r'\d+', a1) # Extract the first chunk of 1+ digits
if num0_m: # If there is a match
rx = r'(?<!\d){}(?!\d)'.format(num0_m.group()) # Set a regex to match the number when not inside other digits
print(re.sub(rx, lambda x: str(int(x.group())+1), a1)) # Increment the matched numbers
# => images2subimages2/folder100/hello2.png
See the Python demo
Related Topics
React Hooks - Right Way to Clear Timeouts and Intervals
Replace Multiple Whitespaces with Single Whitespace in JavaScript String
How to Extend a Class Without Having to Use Super in Es6
How to Match Multiple Occurrences with a Regex in JavaScript Similar to PHP's Preg_Match_All()
How to Set a JavaScript Breakpoint from Code in Chrome
Http Get Request in Node.Js Express
Track Event in Google Analytics Upon Clicking Form Submit
What's the Fastest Way to Convert String to Number in JavaScript
How to Programmatically Force an Onchange Event on an Input
JavaScript Closures and 'This'
Method Overloading in JavaScript
Migrating Angularjs to Angular 4,5 (With Demo)
How to Set Multipart in Axios with React
Style.Display='None' Doesn't Work on Option Tags in Chrome, But It Does in Firefox