【问题标题】:Regex string where space is optional and trim is followed only by (正则表达式字符串,其中空格是可选的,trim 后仅跟 (
【发布时间】:2016-04-20 15:40:10
【问题描述】:

假设我有

string abc = "and TRIM$ ( 000trim) and (trim000) and  (abctrim) and Trim(trima) and  TRIM (  abc  ) and trim( A) and 0trim"

我只想将 TRIM() 函数更改为 RTRIM() 并且希望模式忽略空格(如果有的话)并在 TRIM 之后考虑 (

我正在使用

Regex.Replace(abc, "(?i)([^A-Za-z0-9])TRIM([^A-Za-z0-9][(])", "$1RTRIM(");

上面代码的结果是

"and RTRIM( (000trim) and (trim000) and (abctrim) and Trim(trimaa) and RTRIM(abc) and trim(A) 和 0trim";

我希望输出为

"and TRIM$ (000trim) and (trim000) and (abctrim) and RTRIM(trimaa) and RTRIM (abc) and RTRIM (A) 和 0trim";

我怎样才能获得想要的输出?

【问题讨论】:

    标签: c# regex string trim regex-greedy


    【解决方案1】:

    使用这个:

    Regex.Replace(text, @"\bTRIM(?=\s*\()", "RTRIM", RegexOptions.IgnoreCase)
    

    正则表达式匹配trim,其后紧跟0 个或多个空格(包括制表符)和左括号(RegexOptions.IgnoreCase 是不言自明的......

    编辑:添加一个 (?<![$%]) 以使其忽略 trim 与前导 %$ 像这样:

    Regex.Replace(text, @"\b(?<![$%])TRIM(?=\s*\()", "RTRIM", RegexOptions.IgnoreCase)
    

    【讨论】:

    • 我会使用 \bTRIM(?=\s*\() 作为搜索,以防字符串中已经有其他 RTRIM(或 LTRIM)实例。
    • Regex.Replace(text, @"\bTRIM(?=\s*()", "RTRIM", RegexOptions.IgnoreCase) 当我们有 "and TRIM$ ( 000trim) 和 (trim000 ) and (abctrim) and $trim(_ef** and (trim and **Trim(changetrim)** and **TRIM (abc)** and **trim( A)** and 0trim" .. ......输出是“和TRIM$ (000trim) and (trim000) and (abctrim) and **$trim(_ef and (trim and Trim(changetrim) and RTRIM(abc)trim(A) 和 0trim" @Robert McKee
    • 如果字符串有 %trim(_bla)% 它正在将其更改为 %rtrim(_bla)%.. 如何避免?? @罗伯特·麦基
    • @virtualreality 查看我的修改以进行修复。下次发布新问题,如果您决定在将近一周后更改/添加要求...
    【解决方案2】:

    你可以这样替换:

    var input = @"and TRIM$ ( 000trim) and (trim000) and  (abctrim) and Trim(trima) and  TRIM (  abc  ) and trim( A) and 0trim";
    var pattern = @"(?i)\btrim(?:\s+|)(\([^)]+\))";
    string res = Regex.Replace(input, pattern, "RTRIM$1");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-25
      • 2011-06-19
      • 1970-01-01
      • 2010-12-04
      • 2020-09-30
      • 1970-01-01
      • 2013-10-07
      • 1970-01-01
      相关资源
      最近更新 更多