3

いくつかの異なる Web サイトから電子メール アドレスを抽出したいと考えています。それらがアクティブなリンク形式の場合、次を使用してこれを行うことができます

//A[starts-with(@href, 'mailto:')]

しかし、それらのいくつかはリンクではなく単なるテキスト形式であるため、内部example@domain.comに含まれる要素へのパスを選択したいと思います@

4

2 に答える 2

4

@ を含む要素へのパスを選択したい

使用:

//*[contains(., '@')]

あなたが実際に望んでいたのは、「@」を含むテキストノードの子を持つ要素を選択することだと私には思えます。その場合は、次を使用します。

//*[contains(text(), '@')]

XSLT ベースの検証:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="/">
     <xsl:copy-of select=
        "//*[contains(text(), '@')] "/>
 </xsl:template>
</xsl:stylesheet>

この変換が次の XML ドキュメントに適用された場合:

<html>
 <body>
  <a href="xxx.com">xxx.com</a>
  <span>someone@xxx.com</span>
 </body>
</html>

XPath 式が評価され、選択されたノードが出力にコピーされます

<span>someone@xxx.com</span>
于 2012-04-11T12:30:11.770 に答える
4

おそらく正規表現を使用したいと思うでしょう。ドキュメント内のコンテキストに関係なく、電子メール アドレスを抽出できます。これは、開始するための小さなテスト駆動の例です。

require "minitest/spec"
require "minitest/autorun"

module Extractor
  EMAIL_REGEX = /[\w]+@[\w]+\.[\w]+/

  def self.emails(document)
    (matches = document.scan(EMAIL_REGEX)).any? ? matches : false
  end
end

describe "Extractor" do
  it 'should extract an email address from plaintext' do
    emails = Extractor.emails("email@example.com")
    emails.must_include "email@example.com"
  end

  it 'should extract multiple email addresses from plaintext' do
    emails = Extractor.emails("email@example.com and email2@example2.com")
    emails.must_include "email@example.com", "email2@example2.com"
  end

  it 'should extract an email address from the href attribute of an anchor' do
    emails = Extractor.emails("<a href='mailto:email3@example3.com'>Email!</a>")
    emails.must_include "email3@example3.com"
  end

  it 'should extract multiple email addresses from both plaintext and within HTML' do
    emails = Extractor.emails("my@email.com OR <a href='mailto:email4@example4.com'>Email!</a>")
    emails.must_include "email4@example4.com", "my@email.com"
  end

  it 'should not extract an email address if there isn\'t one' do
    emails = Extractor.emails("email(at)address(dot)com")
    emails.must_equal false
  end

  it "should extract email addresses" do
    emails = Extractor.emails("email.address@domain.co.uk")
    emails.must_include "email.address@domain.co.uk"
  end
end

最後のテストは、正規表現が有効な電子メール アドレスの大部分を予測していないため、失敗します。これを出発点として使用して、より良い正規表現を考え出すか、見つけるかどうかを確認してください。正規表現を作成するには、Rubularを確認してください。

于 2012-04-11T12:20:20.447 に答える