【问题标题】:Regex string replace in c#c#中的正则表达式字符串替换
【发布时间】:2013-10-11 10:57:08
【问题描述】:

我有一个类似

的字符串
var input =  "data1, data2, 1233456,  \"\"\" test, data, here \"\"\", 08976, test data"

我想用test; data; here替换这个字符串的\"\"\" test, data, here \"\"\"部分

简单地说,用分号';' 替换逗号','\"\"\" 块内的任何字符串。

我正在尝试使用正则表达式来做到这一点。

我正在尝试使用以下正则表达式 - \[\\\\\"](.+)[\\\\\"]

【问题讨论】:

  • 继续,将失败的代码尝试添加到您的问题中。它不会使问题更清楚,但它可能会让人们指出你可能有的一个小误解......而且它也让人们更有可能回答这个问题(奇怪,但真实。)
  • 正如@Beska 所说...如果人们知道您已经尝试过,他们更有可能提供帮助。发布您的代码表明

标签: c# regex c#-4.0


【解决方案1】:

仅供参考,如果您想要比较非正则表达式的解决方案,您也可以使用 LINQ 进行此操作:

input= string.Join("\"\"\"", 
         input.Split(new []{"\"\"\""}, StringSplitOptions.None)
         .Select( (s,i) => i % 2 == 1 ? s.Replace (',', ';') : s)
       );

【讨论】:

    【解决方案2】:

    谢谢你的帮助,

    你的回答很有用。

    this link的帮助下,终于用下面的代码做到了

    //My input string
    var input  = Regex.Replace(input  , "[\\\"](.+)[\\\"]", ReplaceMethod);
    
    
    //Method used to replace 
    public static string ReplaceMethod(Match m)
        {
            string newValue = m.Value;
            return newValue.Replace("\"", "").Replace(",", ";");
        }
    

    【讨论】:

      【解决方案3】:

      我认为用正则表达式来处理这个字符串是不可能的:
      data1, 1233456, """ test, data, here """, 08976, test, """ second, data """, aso

      有可能:
      data1, 1233456, < test, data, here >, 08976, test, < second, data >, aso

      但不是“xxx”

      模式:\"{3}.*\"{3}
      foreach 正则表达式匹配此模式 string.replace(',', ';')

      但我正在尝试制作正则表达式...
      我放弃了:/

      【讨论】:

      • 请检查我的答案,有可能
      【解决方案4】:

      以下代码可能满足要求...

      var output = Regex.Replace(input , "(?

      【讨论】:

      • 我认为这个字符串的正则表达式不可能做到这一点:data1, 1233456, """ test, data, here """, 08976, test, """ second, data """, aso
      • 能确认输入的是data1,data2,1233456,”””test,data,这里是”””,08976,testdata(不带转义字符)吗?
      • 当你在 Regex.Replace 上运行时,你应该得到...data1, data2, 1233456, """ test; data; here """, 08976, test data (没有转义)。让我知道这是否是您正在寻找的。​​span>
      • 你可以在这里测试:fiddle.re/5mawn 但即使你解决了这个问题,它对于 """ 之后和下一个 """ 开始之前的数据也是正确的
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-13
      • 2017-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多