代码之家  ›  专栏  ›  技术社区  ›  Omegaspard

在一个模式中提取一个动态值以将其放入另一个模式中

  •  0
  • Omegaspard  · 技术社区  · 6 年前

    Formula1(value) + Formula2(anotherValue) * 0.5
    

    哪里 Formula1 Formula2 常量 正则表达式 将初始字符串转换为

    Formula1(value, constantWord) + Formula2(anotherValue, constantWord) * 0.5
    

    在这里 value anotherValue 等等,是一连串的 大写字母 数字 可以由 2 3

    的正则表达式 s很简单。但剩下的部分对我来说更难。

    我怎么能这样做呢 C级# ?

    Swipe(YN1) + Avg(DNA) * 0.5
    

    预期结果:

    Swipe(YN1, calculated) + Avg(DNA, calculated) * 0.5
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Dmitry Bychenko    6 年前

    你可以试试 向前看 向后看

    (?<=[A-Za-z][A-Za-z0-9]*\s*\(\s*)[A-Z0-9]{2,3}(?=\s*\))
    

    我们有简单的 比赛 感兴趣的 [A-Z0-9]{2,3} 2 3 大写字母 数字 . 但是这个 比赛 应该是 之后 Swipe( Formula1( )以及 之前 ) . 假设 成为一个 标识符

    (?<=  )      - group, behind: should appear before the match; will not be included into it
    [A-Za-z]     - one letter (Formula1)
    [A-Za-z0-9]* - letters or digits, zero or more
    \s*          - whitespaces (spaces, tabultalions) - zero or more
    

    匹配

    [A-Z0-9]{2,3} - Capital letters or digits from 2 to 3 characters 
    

    最后我们应该看看 向前地 为了找出右括号:

    (?= ) - group, ahead: should appear before the match; will not be included into it
    \s*   - zero or more whitespaces (spaces, tabulations etc)      
    \)   - closing parenthesis (escaped)
    

    合并,我们有

    (?<=[A-Za-z][A-Za-z0-9]*\s*\(\s*) -- Behind:
                                      --   Letter, zero or more letters or digits, parenthesis 
    
    [A-Z0-9]{2,3}                     -- Value to match (2..3 capital letters or digits)
    
    (?=\s*\)                          -- Ahead: 
                                      --   Closing parenthesis 
    

    (?<=[A-Za-z][A-Za-z0-9]*\s*\(\s*)[A-z0-9]{2,3}(?=\s*\)
    

    看到了吗 https://www.regular-expressions.info/lookaround.html 有关详细信息

    C级# 代码:

    string source = @"Swipe(YN1) + Avg(DNA) * 0.5";
    string argument = "calculate";  
    
    string result = Regex.Replace(
        source, 
      @"(?<=[A-Za-z][A-Za-z0-9]*\s*\(\s*)[A-Z0-9]{2,3}(?=\s*\))", 
        match => match.Value + $", {argument}");
    
    Console.Write(result);
    

    Swipe(YN1, calculate) + Avg(DNA, calculate) * 0.5