0

我想使用正则表达式(最好在 sublimetext2 中)来替换以下内容:

<td class="etword">et alfabet</td>
<td class="etword">&nbsp;</td>

有了这个:

<td class="etword">et alfabet</td>
<td class="etword"><?php audioButton("../../audio/words/et_alfabet","et_alfabet");?></td>

非常感谢!

4

2 回答 2

2
于 2013-04-29T07:39:16.287 回答
0

使用 HTMLAgility http://htmlagilitypack.codeplex.com/之类的 HTML 解析器可以更轻松地完成此类活动


关于最佳方式的足够的讲座。我想您正在寻找捕获第一个 etword 内部文本并将其拉入替换字段。

我敢肯定这可以在崇高的重写。在 powershell 中,我将通过以下方式完成此操作:

$Matches= @()
$String =  '<td class="etword">et alfabet</td>
<td class="etword">&nbsp;</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"[^>]*?>&nbsp;</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 &nbsp; with the correct text
    $NewString = $WholeMatchingString -replace "&nbsp;", $('<?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

产生以下输出:

Found Text:  et alfabet
WholeMatchingString:  <td class="etword">et alfabet</td><td class="etword">&nbsp;</td>
NewString:  <td class="etword">et alfabet</td><td class="etword">&nbsp;</td>
Result:  <td class="etword">et alfabet</td><td class="etword"><?php audioButton("../../audio/words/et alfabet","et alfabet");?></td>

在 powershell 中, $Matches 数组会自动填充最后一次匹配操作的结果。

于 2013-04-29T01:30:00.757 回答