[英]sed (regex) not working properly
我必須從以下一段 HTML 代碼中分離出一個表達式:
<div class="summary">
<h3><a href="/questions/30727515/why-is-executing-java-code-in-comments-allowed" class="question-hyperlink" title="The following code produces the output "Hello World!". (No really, try it) public static void main(String... args) { // The comment below is no typo. // \u000d System.out.println("Hello ...">Why is executing Java code in comments allowed?</a></h3>
<div class="tags t-java t-unicode">
<a href="/questions/tagged/java" class="post-tag" title="show questions tagged 'java'" rel="tag">java</a> <a href="/questions/tagged/unicode" class="post-tag" title="show questions tagged 'unicode'" rel="tag">unicode</a>
</div>
<div class="started">
<a href="/questions/30727515/why-is-executing-java-code-in-comments-allowed/?lastactivity" class="started-link">modified <span title="2015-06-15 17:43:58Z" class="relativetime">yesterday</span></a>
<a href="/users/388520/zwol">zwol</a> <span class="reputation-score" title="reputation score 52560" dir="ltr">52.6k</span>
</div>
</div>
我想要的部分從 .... 'title="下面的代碼產生輸出 ..... 在允許的注釋中執行 Java 代碼嗎? 一直到 'a' 和 'h3' 標簽的結尾。
由於各種原因,我只能使用 sed 或 awk。
我嘗試了各種正則表達式。 由於所需部分有時甚至可能跨越多行,我使用了以下 sed 命令:(因為 .* 僅匹配換行符)
sed -n '1h;1!H;${;g;s/.*<h3><a href="\/questions\/.*link" title="\(.*\)<\/a><\/h3>.*/\1/p;}' Trial.html
我沒有得到任何結果。 但是,如果我刪除結束部分:
sed -n '1h;1!H;${;g;s/.*<h3><a href="\/questions\/.*link" title="\(.*\)/\1/p;}' Trial.html
我能夠捕捉到所需字符串的開頭並打印到最后。
我也提到了這個 serverfault.com 問題,尋求幫助: https : //serverfault.com/questions/315145/regex-for-sed-to-grab-multiple-lines-or-a-better-way
編輯:
也可能有其他類似的塊。 我不必停留在第一個結果上。 我已經從這個頁面獲取了 html: https : //stackoverflow.com/?tab=month
這是另一個與我非常相似的問題! https://unix.stackexchange.com/questions/64645/text-between-two-tags
你的線路
sed -n '1h;1!H;${;g;s/.*<h3><a href="\/questions\/.*link" title="\(\.*\)<\/a><\/h3>.*/\1/p;}' Trial.html
該行將所有內容放在保持空間中,然后在讀取文件后將其交換到模式空間以用於多行解析。
修改想法,而不是分組 \\(\\.*\\) 順便說一下,這是不正確的,因為你已經在這里轉義了 '.' 所以它不是任何字符,而是文字 '.'
您可以使用 title="\\([^<]*\\) 它將捕獲所有字符,直到第一個 '<'。
此外,如果 title=" 在文件中只出現一次,那么模式的第一部分不需要很多字母,只有 ^.*title=" 就足夠了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.