Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math operations in regex

Tags:

regex

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.

like image 459
Kevin Avatar asked Mar 09 '11 11:03

Kevin


People also ask

What is difference [] and () in regex?

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.

What is regex math?

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.

What is regex operation?

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.

How do you test expressions in regex?

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.


2 Answers

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.

like image 192
Metaphox Avatar answered Sep 25 '22 10:09

Metaphox


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 
like image 41
Bart Kiers Avatar answered Sep 25 '22 10:09

Bart Kiers