Kotlin замена строки - PullRequest
       0

Kotlin замена строки

0 голосов
/ 04 февраля 2020

Как заменить строку в kotlin? У меня есть пример здесь с html строкой.

var test = "<html><body><p> just some test text</p> And i wanna use this text for texting and i ll show you this image https://www.instagram.com/p/B8I9_KiF45g/?utm_source=ig_web_copy_link also this is the instagram photo with just normal link id body https://www.instagram.com/p/B8I3r66pVpp/ <h> random title text </h></body></html>"

Есть ли возможность добавлять только ссылки Instagram в тегах

"<html><body><p> just some test text</p> And i wanna use this text for texting and i ll show you this image <iframe src="https://www.instagram.com/p/B8I9_KiF45g/embed"> </iframe> also this is the instagram photo with just normal link id body <iframe src="https://www.instagram.com/p/B8I3r66pVpp/embed" </iframe> <h> random title text </h></body></html>"

Ответы [ 2 ]

1 голос
/ 05 февраля 2020

Это не идеально (так как соответствие регулярному выражению HTML имеет некоторые проблемы ), но оно может работать для вашего конкретного c варианта использования и по крайней мере должно помочь вам начать. Он использует комбинацию RegEx и replace (в составе функции расширения) для поиска ссылок и их встраивания:

fun String.embedded(): String {
    // Match everything starting with https://www.instagram.com/ until the first question mark, whitespace or new tag.
    // The second group is used to get rid of any query parameters.
    val linkRegex = "(https://www.instagram.com/[^\\? <]*)(\\?[^ <]*)?".toRegex()
    // $1 is the first matching group, i.e. the link itself.
    val output = this.replace(linkRegex, """<iframe src="$1embed"> </iframe>""")
    return output
}

Краткий пример для предоставленные вами данные:

fun main() {
    val input = "<html><body><p> just some test text</p> And i wanna use this text for texting and i ll show you this image https://www.instagram.com/p/B8I9_KiF45g/?utm_source=ig_web_copy_link also this is the instagram photo with just normal link id body https://www.instagram.com/p/B8I3r66pVpp/ <h> random title text </h></body></html>"
    val expected = """<html><body><p> just some test text</p> And i wanna use this text for texting and i ll show you this image <iframe src="https://www.instagram.com/p/B8I9_KiF45g/embed"> </iframe> also this is the instagram photo with just normal link id body <iframe src="https://www.instagram.com/p/B8I3r66pVpp/embed"> </iframe> <h> random title text </h></body></html>"""

    val output = input.embedded()
    println(output)
    println(output == expected)
}
1 голос
/ 04 февраля 2020

Я бы проанализировал строку html с указанной библиотекой c, например DOMParser- kotlin, а затем l oop для фреймов и изменил атрибуты sr c

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...