grep /regex to do iteration / incrementation
I keep running into situations where I need to have incremented variables but I haven't figured out a way to script that so I end up coding it in by hand which is awful when there are a ton of entires. I found a code on this site that I thought would work but my text editor (TextWragler) did not like it (or I didn't do something right). This was the example:
Initial Contents: Var22 Var20 Var86 Var30
Search String: Var*[0-9]
Replace String: Var%1>49>
Results: Var50 Var51 Var52 Var53
The replace string just returned as itself.
I'm going to use it to increment something along the lines of:
<span id="x">something</span> <span id="x">else</span> <span id="x">entirely</开发者_JAVA百科span>
the value x should be replaced as x1, x2, x3 or some other "string" + n. It would be ideal if it could recognize and renumber mis-numbered variables like that grep code suggests.
Any idea how I can make this work? Can I not use textWrangler? ThanksOn a side note I'm trying to get better at javascript and I'm really curious as to how I could implement something like this(grep/incrementation of strings) into a javascript?
Not sure what you want, but if you want to apply an (arithmetic or other) operation on say the number part after 'Var', you can do something like that using a delegate function
'Var22 Var20 Var86 Var30'
.replace(/(Var)(\d+)/g,
function(a,b,c){return b+(Number(c)+10)}
); //=> Var32 Var30 Var96 Var40
In javascript regular expressions the %
-sign is $
and the index of matches starts with 1. If you just want to replace the number in 'Var12` with 9, it looks like this:
'Var12'.replace(/(Var)(\d+)/,'$19'); //=> Var9
// Var (=$1) ^^^ ^ 1 or more numbers (=$2)
This webpage gives you more information about javascript Regular Expressions
精彩评论