c# - 递归解析字符串

标签 c# regex

我正在尝试从字符串中提取信息 - 具体来说是一个 Fortran 格式字符串。字符串的格式如下:

F8.3, I5, 3(5X, 2(A20,F10.3)), 'XXX'

格式字段由“,”分隔,格式组位于括号内,括号前的数字表示格式模式连续重复的次数。因此,上面的字符串扩展为:

F8.3, I5, 5X, A20,F10.3, A20,F10.3, 5X, A20,F10.3, A20,F10.3, 5X, A20,F10.3, A20,F10.3, 'XXX'

我正在尝试用 C# 做一些事情来扩展符合该模式的字符串。我已经开始使用大量的 switch 和 if 语句来解决这个问题,但我想知道我是否没有以错误的方式处理它?

我基本上想知道是否有一些 Regex wizzard 认为正则表达式可以一口气做到这一点?我对正则表达式一无所知,但如果这可以解决我的问题,我正在考虑花一些时间来学习如何使用它们……另一方面,如果正则表达式不能解决这个问题,那么我宁愿花我的时间有时间看看另一种方法。

最佳答案

这必须用正则表达式来实现:) 我已经扩展了我之前的例子,它很好地测试了你的例子。

// regex to match the inner most patterns of n(X) and capture the values of n and X.
private static readonly Regex matcher = new Regex(@"(\d+)\(([^(]*?)\)", RegexOptions.None);

// create new string by repeating X n times, separated with ','
private static string Join(Match m)
{
    var n = Convert.ToInt32(m.Groups[1].Value); // get value of n
    var x = m.Groups[2].Value; // get value of X
    return String.Join(",", Enumerable.Repeat(x, n));
}

// expand the string by recursively replacing the innermost values of n(X).
private static string Expand(string text)
{
    var s = matcher.Replace(text, Join);
    return (matcher.IsMatch(s)) ? Expand(s) : s;
}

// parse a string for occurenses of n(X) pattern and expand then.
// return the string as a tokenized array.
public static string[] Parse(string text)
{
    // Check that the number of parantheses is even.
    if (text.Sum(c => (c == '(' || c == ')') ? 1 : 0) % 2 == 1)
        throw new ArgumentException("The string contains an odd number of parantheses.");

    return Expand(text).Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
}

关于c# - 递归解析字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9096811/

相关文章:

java - 相同正则表达式的模式/匹配器与 String.split()

jQuery 验证 - 验证特定字段按键的特定规则/方法

java - java中使用模式匹配提取数据

regex - linux/unix 中的模式匹配或 RegEx 手册页?

c# - Parallel.For 在列表中,仅在开始时按顺序对项目进行操作

c# - 如何从 SQL 数据库中获取数据以存储到组合框中 - C#

c# - WriteableBitmap 周围出现不需要的红色边框

c# - 关于验证用户登录名和密码的问题

c# - EF6 子实体未以多对多关系更新

用于简单问题的 Python 正则表达式