Строка. Исключение формата, когда строка формата содержит “{”

Groovy 17B:

p={it==it[-1..0]}

Оборотная сторона - то, что это не работает со строкой emptry.

Вообще-то, если задуматься, выдавая исключение для пустой строки разумен, так как Вы не можете сказать, не является ли ничто палиндромом или нет.

31
задан John Saunders 15 July 2009 в 17:31
поделиться

5 ответов

At a guess, the html contains javascript or another source of braces ({ and }) which would all need doubling (to {{ and }}) to be usable with string.Format. I expect a different (more obvious) token may be in order, i.e. %%FILENAME%%. Then use either regex or string.Replace.

If you have a single tag, string.Replace is fine; if you have lots, there are tricks with regex and MatchEvaluator that may be helpful - like so but with a different regex pattern.


Update after the example html added: I would definitely use a different token; at the most basic level:

<param name="initParams" value="cc=true,markers=true,m=%%FILENAME%%" />

and

template = template.Replace("%%FILENAME%%", "video.wmv");
60
ответ дан 27 November 2019 в 21:43
поделиться

Wat are the contents of the 'template' variable ?

Difficult to say what 's wrong with your code, but presumably, the template variable does not contain a string which as a place-holder. (Например, «это некоторая строка {0}».)

Я думаю, что вам следует использовать инструменты, которые предоставляет ваша IDE: отладить код, использовать часы для проверки содержимого переменной шаблона.

1
ответ дан 27 November 2019 в 21:43
поделиться

Что находится в файле шаблона?

если есть фигурные скобки, которые не относятся к формату {int} или их больше, чем аргументов для оператора формата, он выдаст исключение.

Какое сообщение в исключении?

Это ваш CSS. Как упоминалось ранее, вам нужно будет выполнить замену регулярного выражения или кучу команд String.Replace в строке, пометьте переменные с помощью %% VARIABLE_NAME %% и используйте замену строк, чтобы заменить их

0
ответ дан 27 November 2019 в 21:43
поделиться

string.Format() does not handle { and } in the format string. You need to replace { with {{ and } with }} everywhere in your template.html file. Except for the single place where you use the {0} placeholder.

Not very elegant.

Instead, consider using a template engine. See http://csharp-source.net/open-source/template-engines for some suggestions.

The next-best solution is to use regexes (with MatchEvaluator) or string.Replace(), as suggested by other answers.

Edit:

Here's an example using the StringTemplate template engine:

StringTemplate htmlpage = new StringTemplate(File.ReadAllText("template.html"));
htmlpage.SetAttribute("content", "video.wmv");
Console.WriteLine(htmlpage.ToString());

Change a single line in your template.html file:

from:

<param name="initParams" value="cc=true,markers=true,m={0}" />

to:

<param name="initParams" value="cc=true,markers=true,m=$content$" />

When the template engine encounters $content$ in the template, it replaces it with the value of the 'content' attribute that you set using code.

Using StringTemplate, you can do simple looping and conditionals within your template. See the documentation.

6
ответ дан 27 November 2019 в 21:43
поделиться

Ваш шаблон содержит { и } символов, которые необходимо экранировать, иначе они запутают String.Format . Спасайтесь от них, используя {{ и }} . В качестве альтернативы можно использовать другой механизм, например String.Replace .

16
ответ дан 27 November 2019 в 21:43
поделиться
Другие вопросы по тегам:

Похожие вопросы: