1

次のテキストにhtmlコンテンツがあります。

    "This is my text to be parsed which contains url 
    http://someurl.com?param1=foo&params2=bar 
 <a href="http://thisshouldnotbetampered.com">
    some text and a url http://someotherurl.com test 1q2w
 </a> <img src="http://someasseturl.com/abc.jpeg"/>
    <span>i have a link too http://someurlinsidespan.com?xyz=abc </span> 
    "

プレーン URL をハイパーリンクに変換する正規表現が必要です (既存のハイパーリンクを改ざんせずに)

期待される結果:

    "This is my text to be parsed which contains url 
    <a href="http://someurl.com?param1=foo&params2=bar">
http://someurl.com?param1=foo&params2=bar</a> 
 <a href="http://thisshouldnotbetampered.com">
    some text and a url http://someotherurl.com test 
1q2w </a> <img src="http://someasseturl.com/abc.jpeg"/>
    <span>i have a link too <a href="http://someurlinsidespan.com?xyz=abc">http://someurlinsidespan.com?xyz=abc</a> </span> "
4

4 に答える 4

3

免責事項:このタスクには正規表現を使用しないでください。html パーサーを使用してください。これは、適切にフォーマットされた HTML を期待する場合に可能であることを実証するためのPOCです (いずれにせよ、それはありません)。

だからここに私が思いついたものがあります:
(https?:\/\/(?:w{1,3}.)?[^\s]*?(?:\.[a-z]+)+)(?![^<]*?(?:<\/\w+>|\/?>))

これは何を意味するのでしょうか ?

  • (: グループ 1
  • https?: 一致httpまたはhttps
  • \/\/: マッチ//
  • (?:w{1,3}.)?: オプションで一致w.ww.またはwww.
  • [^\s]*?: 空白以外のすべてに 0 回以上一致します
  • (?:\.[a-z]+)+): ドットとそれに続く[a-z]文字に一致し、これを 1 回以上繰り返します
  • (?!: 否定先読み
    • [^<]*?: <0 回以上 ungreedyを除くすべてに一致
    • (?:<\/\w+>|\/?>): 終了タグまたは/>またはに一致>
    • ): 先読みの終わり
  • ): グループ 1 の終わり


                           regex101 online demo                                            rubular online demo

于 2013-06-11T08:20:18.500 に答える
0

私はこのようなことをします:

require 'nokogiri'

doc = Nokogiri::HTML.fragment <<EOF
This is my text to be parsed which contains url 
http://someurl.com  <a href="http://thisshouldnotbetampered.com">
some text and a url http://someotherurl.com test 1q2w </a> <img src="http://someasseturl.com/abc.jpeg"/>
EOF

doc.search('*').each{|n| n.replace "\n"}

URI.extract doc.text
#=> ["http://someurl.com"]
于 2013-06-11T09:43:36.453 に答える
0

http://rubular.com/を試してみてくださいRegex。目的の出力を得るのに役立つヒントがいくつかあります。

于 2013-06-11T08:23:23.813 に答える