问题
I would like to use regex (preferably in sublimetext2) to replace the following:
<td class="etword">et alfabet</td>
<td class="etword"> </td>
with this:
<td class="etword">et alfabet</td>
<td class="etword"><?php audioButton("../../audio/words/et_alfabet","et_alfabet");?></td>
Thanks very much!
回答1:
Sublime Text
Find what:
<td class="etword">(.*?)</td>\n<td class="etword"> </td>
Replace with
<td class="etword">$1</td>\n<td class="etword"><?php audioButton("../../audio/words/$1","$1");?></td>
This will fill the second table cell. However in the URL there will be spaces if there were spaces in the first cell. Unfortunately just regular expressions cannot do that, so we have to use some other features of Sublime Text to get it done.
Search (CTRL+F) for audioButton\(".*?\);
and click “Find All”. That way, all the audioButton
-calls will be selected. Then, without clicking anything else, open up the search/replace panel again (CTRL+H) and replace (space character) with
_
(underscore). Make sure that the “In selection”-option is activated. Then click “Replace All” and everything should be fine.
回答2:
This type of activity would be easier done with an HTML parser like HTMLAgility http://htmlagilitypack.codeplex.com/
Enough lecturing on the best way. I presume you're looking to capture the first etword inner text and pull that into the replacement field.
I'm sure this can be rewritting in sublime. In powershell I'll accomplish that with something like this:
$Matches= @()
$String = '<td class="etword">et alfabet</td>
<td class="etword"> </td>'
# find the value in the preceding cell. if there arn't any matching strings then skip
if ($String -imatch '<td[^>]*class="etword"[^>]*?>([^<]*?)</td>[\s\n]*?<td[^>]*class="etword"[^>]*?> </td>' ) {
$FoundText = $Matches[1]
$WholeMatchingString = $Matches[0]
write-host "Found Text: " $FoundText
write-host "WholeMatchingString: " $WholeMatchingString
# create a new string with the desired values, by replacing with the correct text
$NewString = $WholeMatchingString -replace " ", $('<?php audioButton("../../audio/words/' + $FoundText + '","' + $FoundText + '");?>')
Write-Host "NewString: " $NewString
# replace the whole matcing string with the New string
$String = $String -replace $WholeMatchingString, $NewString
Write-Host "Result: " $String
} # end if
Yields the following output:
Found Text: et alfabet
WholeMatchingString: <td class="etword">et alfabet</td><td class="etword"> </td>
NewString: <td class="etword">et alfabet</td><td class="etword"> </td>
Result: <td class="etword">et alfabet</td><td class="etword"><?php audioButton("../../audio/words/et alfabet","et alfabet");?></td>
In powershell the $Matches array is populated automatically with the results from the last -match operation.
来源:https://stackoverflow.com/questions/16269122/replace-using-regex-in-sublimetext2