我有一个包含"https://tryout.pendukasi.id/upload/"的字符串,我想将每个包含"https://tryout.pendukasi.id/upload/"的字符串替换为"data:image/jpeg;基数64"。
法典:
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 ….</p>"
,则字符串未成功更改。如何解决这个问题?
发生这种情况是因为您正在逐个文件替换,并且之前的更改不断被以下更改:
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);
}
}