Как написать шаблон регулярного выражения C #, чтобы он соответствовал основным строкам формата printf, таким как "% 5.2f"? - PullRequest
3 голосов
/ 04 ноября 2010

Он должен соответствовать следующим критериям (условные части указаны в квадратных скобках:

%[some numbers][.some numbers]d|f|s

Обозначение d | f | s означает, что один из них должен быть там.

Спасибо & BR -Matti

Ответы [ 3 ]

3 голосов
/ 04 ноября 2010

Это должно сделать это:

string input = "Bloke %s drank %5.2f litres of water and ate %d bananas";
string pattern = @"%(\d+(\.\d+)?)?(d|f|s)";

foreach (Match m in Regex.Matches(input, pattern))
{
    Console.WriteLine(m.Value);
}

Я не использовал [dfs] в своем шаблоне, так как планировал обновить его для использования именованных групп. Это основано на вашем предыдущем вопросе о поиске стратегии замены строк формата в стиле C.

Вот идея:

string input = "Bloke %s drank %5.2f litres of water and ate %d bananas";
string pattern = @"%(?<Number>\d+(\.\d+)?)?(?<Type>d|f|s)";

int count = 0;
string result = Regex.Replace(input, pattern, m =>
{
    var number = m.Groups["Number"].Value;
    var type = m.Groups["Type"].Value;
    // now you can have custom logic to check the type appropriately
    // check the types, format with the count for the current parameter
    return String.Concat("{", count++, "}");
});

C # /. NET 2.0 подход:

private int formatCount { get; set; }

void Main()
{
    string input = "Bloke %s drank %5.2f litres of water and ate %d bananas";
    Console.WriteLine(FormatCStyleStrings(input));  
}

private string FormatCStyleStrings(string input)
{
    formatCount = 0; // reset count
    string pattern = @"%(?<Number>\d+(\.\d+)?)?(?<Type>d|f|s)";
    string result = Regex.Replace(input, pattern, FormatReplacement);
    return result;
}

private string FormatReplacement(Match m)
{
    string number = m.Groups["Number"].Value;
    string type = m.Groups["Type"].Value;
    // custom logic here, format as needed
    return String.Concat("{", formatCount++, "}");
}
2 голосов
/ 05 октября 2011

Вот выражение, соответствующее всем полям строк формата функций printf / scanf.

(?<!%)(?:%%)*%([\-\+0\ \#])?(\d+|\*)?(\.\*|\.\d+)?([hLIw]|l{1,2}|I32|I64)?([cCdiouxXeEfgGaAnpsSZ])

Он основан на Спецификация полей формата .Согласно этой спецификации %[flags][width][.precision][{h|l|ll|L|I|I32|I64|w}]type группы совпадений будут содержать: #1 - flags, #2 - width, #3 - precision, #4 - size prefix, #5 - type.

Взято из здесь .

2 голосов
/ 04 ноября 2010
%(?:\d+)?(?:\.\d+)?[dfs]

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

...