-2

我有一个包含“ https://tryout.pendukasi.id/upload/ ”的字符串,我想将每个包含“ https://tryout.pendukasi.id/upload/ ”的字符串替换为“data:image/jpeg; base64"。

代码:

foreach (StorageFile file in files)
{
    string soalP = file.Path;
    if (question.Pertanyaan.ToString().Contains("https://tryout.pendidikan.id/upload/"))
    {
        byte[] imageArray = System.IO.File.ReadAllBytes(soalP);
            string base64ImageRepresentation = Convert.ToBase64String(imageArray);
            soal = Regex.Replace(question.Pertanyaan.ToString(), "\"https://tryout.pendidikan.id/upload/" + file.Name + "\"", "data:image/jpeg;base64," + base64ImageRepresentation);
    }
}

我有一个问题,如果字符串包含一个“ https://tryout.pendukasi.id/upload/ ”,则该字符串已成功替换,但如果它包含多个“ https://tryout.pendukasi.id/upload / ",例如 : "<p>Perhatikan ayat-ayat Surat al-Falaq berikut ini!<br /><img src=\"https://tryout.pendidikan.id/upload/3-1.JPG\" /><br /><img src=\"https://tryout.pendidikan.id/upload/3-2.JPG\" /><br /><img src=\"https://tryout.pendidikan.id/upload/3-3.JPG\" /><br /><img src=\"https://tryout.pendidikan.id/upload/3-4.JPG\" /><br /><img src=\"https://tryout.pendidikan.id/upload/3-5.JPG\" /><br />Urutan ayat dalam Surat al-Falaq yang benar adalah &hellip;.</p>",则字符串未成功更改。如何解决这个问题呢?

4

1 回答 1

0

发生这种情况是因为您正在逐个文件替换文件,并且之前的更改不断被更改:

soal = Regex.Replace(question.Pertanyaan.ToString(), "\"https://tryout.pendidikan.id/upload/" + file.Name + "\"", "data:image/jpeg;base64," + base64ImageRepresentation);

一种方法是将您的正则表达式替换字符串保存到变量中。通过这样做,您的替换不会被覆盖:

string soal = question.Pertanyaan.ToString();

foreach (StorageFile file in files)
{
    string soalP = file.Path;
    if (soal.Contains("https://tryout.pendidikan.id/upload/"))
    {
        byte[] imageArray = System.IO.File.ReadAllBytes(soalP);
            string base64ImageRepresentation = Convert.ToBase64String(imageArray);
            soal = Regex.Replace(soal, "\"https://tryout.pendidikan.id/upload/" + file.Name + "\"", "data:image/jpeg;base64," + base64ImageRepresentation);
    }
}
于 2019-10-08T02:21:15.660 回答