I need to add a number to a backreference while doing a replace operation.
e.g. I am rewriting a URL
www.site.com/doc.asp?doc=321&language=1
to
www.site.com/headline/100321.article
I'm doing a simple replace, but I need to add 100,000 to the doc ID. What I have below works so far without adding anything.
s/.*doc=(\d+).*/www.site.com\/headline\/$1.article/g;
How can I add 100,000 to $1
?
Note, you can't just add 100
before the number because the doc ID might be > 999.
This answer is not useful. Show activity on this post. [] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.
Regular expressions are a generalized way to match patterns with sequences of characters. They define a search pattern, mainly for use in pattern matching with strings, or string matching, i.e. “find and replace” like operations.
A regular expression (shortened as regex or regexp; sometimes referred to as rational expression) is a sequence of characters that specifies a search pattern in text. Usually such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation.
To test a regular expression, first search for errors such as non-escaped characters or unbalanced parentheses. Then test it against various input strings to ensure it accepts correct strings and regex wrong ones. A regex tester tool is a great tool that does all of this.
using Perl:
s/.*doc=(\d+).*/"www.site.com\/headline\/".($1+100000).".article"/e;
as you've done with e flag, the right part becomes now an expression. so you have to wrap the non-capture part as strings.
That's not possible in regex. Regex only matches patterns, it doesn't do arithmetic.
The best you can do is something verbose like:
match replace (\d{6,}) $1 (\d{5}) 1$1 (\d{4}) 10$1 (\d{3}) 100$1 (\d{2}) 1000$1 (\d) 10000$1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With