问题
In the below HTML part, I want to replace, whenever a text is found, with an incremental variable:
<li class="cat-item">
<a href="#" >Beautiful Reclessness</a>
</li>
<li class="cat-item">
<a href="#" >Comfort vs. Appearance</a>
</li>
<li class="cat-item">
<a href="#" >Highlights of the Runway</a>
<ul class='children'>
<li class="cat-item">
<a href="#" >Christian Louboutin Show</a>
</li>
<li class="cat-item">
<a href="#" >Givenchy F/W 2016</a>
</li>
<li class="cat-item">
<a href="#" >Spring by Gaultier</a>
To this using the x++ increment:
<li class="cat-item">
<a href="#" >x1</a>
</li>
<li class="cat-item">
<a href="#" >x2</a>
</li>
<li class="cat-item">
<a href="#" >x3</a>
<ul class='children'>
<li class="cat-item">
<a href="#" >x4</a>
</li>
<li class="cat-item">
<a href="#" >x5</a>
</li>
<li class="cat-item">
<a href="#" >x6</a>
Is there a way in Notepad++ or Vim (looking for in between > <) to do find the text contents using REGEX and replace them with an x counter?
回答1:
Simple vim answer:
- Open the file—
vim filename - Set up a convenience variable—
:let num=1 - Do the replaclement—
:g/href/execute printf("normal! citx%d", num) | let num=num+1
The :global command allows one to perform an operation all lines matching a pattern (in this case, href). The operation we want to do is change the text inside the <a> tag to x followed by the contents of num, and increment num.
execute lets us build a command line from strings; I often combine with printf() because I find it easier to read. normal! is an Ex-command that lets us execute normal-mode commands. cit is a vim'ism for "change inside tag" from normal mode. Then we just feed it the appropriate replacement text (x%d) and increment the counter.
If you're wondering how I came up with this, it's a pretty well-established pattern among vimmers. In practice, it took me probably about a minute to get the whole sequence done (faster if I used it more often), so it isn't one of those "spend 30 minutes trying to write a good regex" answers—this can be done in a live editing session without too much thought, if the person editing has a good grasp of vim fundamentals.
回答2:
Hope that helps.
- Download python script plugin
- plugins > python script > new script > save as "increment.py"
Develop your regex at regex101 or somewhere else and write the script
i=0
def increment(match):
global i
i=i+1
return "x"+str(i)
editor.rereplace('(?<=>)\\b[^><]+', increment)
Save and run your script: plugins > python script > scripts > increment
来源:https://stackoverflow.com/questions/54380185/replacing-html-text-elements-with-increment-variable