正規表現で文字を置換

タグの編集
投稿者 xvmmtnk  (中学生) 投稿日時 2011/10/2 14:09:11
YouTubeの動画を閲覧できるビュアーを作っているのですが、
時々、&~=~ ("&feature=feedf"←この様なもの) というのが後ろについていて、コレがあると、動画を読み込めないので、消したいのですが、どうすれば消せるでしょうか?

    Public Shared Function Y_View(ByVal y_adress As String)
        Dim change As String = Nothing
        Dim source As String = Nothing
        If y_adress.Contains("www.youtube.com/watch?v="Then
            change = y_adress
            change = change.Replace("watch?v=""embed/")
            change = change.Replace("\&.*\n"Nothing'正規表現を使って、"&feature=feedf"を消したいのですが、上手く動きません。 
            source = "<body style=""padding:0;margin:0;""><iframe width=""100%"" height=""100%"" src=" & change & " frameborder=""0"" allowfullscreen></iframe>"
            MsgBox(source) 'change = change.Replace("watch?v=", "embed/") だけが適用されたソースが表示されてしまいます。 
        Else
            MsgBox("YouTubeの動画のアドレスを指定してください。", MsgBoxStyle.OkOnly, "エラー")
        End If
        Return source
        change = Nothing
        source = Nothing
    End Function
投稿者 YuO  (社会人) 投稿日時 2011/10/2 18:59:39
String.Replaceは,単純に文字列を置換する機能しか持ち合わせません。
正規表現を使う場合は,System.Text.RegularExpressions.Regexクラスを使います。

References)
MSDN: String.Replace メソッド (String, String) (System)
http://msdn.microsoft.com/ja-jp/library/fk49wtc1.aspx
MSDN: Regex クラス (System.Text.RegularExpressions)
http://msdn.microsoft.com/ja-jp/library/system.text.regularexpressions.regex.aspx
投稿者 xvmmtnk  (中学生) 投稿日時 2011/10/8 11:30:43
ありがとうございます!
下の文でちゃんと置換されました!
Private Sub Button2_Click(ByVal sender As System.ObjectByVal e As System.EventArgs) Handles Button2.Click
        WebBrowser1.DocumentText = Y_View(TextBox1.Text)
    End Sub

    Public Shared Function Y_View(ByVal y_adress As String)
        Dim change As String = Nothing
        Dim source As String = Nothing
        If y_adress.Contains("www.youtube.com/watch?v="Then
            change = y_adress
            change = change.Replace("watch?v=""embed/")
            change = change.Replace("\&.*\n"Nothing)
            If Regex.IsMatch(change, "\&"Then
                change = Regex.Replace(change, "\&.*""")
            End If
            source = "<body style=""padding:0;margin:0;""><iframe width=""100%"" height=""100%"" src=""" & change & """ frameborder=""0"" allowfullscreen></iframe>"
            MsgBox(source)
        Else
            MsgBox("YouTubeの動画のアドレスを指定してください。", MsgBoxStyle.OkOnly, "エラー")
        End If
        Return source
        change = Nothing
        source = Nothing
    End Function