【问题标题】:I have a textfile and I want to replace a string in it with empty string but我有一个文本文件,我想用空字符串替换其中的一个字符串,但是
【发布时间】:2012-07-27 19:10:21
【问题描述】:

我还想删除之后的字符串,直到下一个逗号,如果该字符串在“select”之后,那么我想在 select 之后替换任何内容,直到下一个逗号。 例如: 从 mytable 中选择 a.column、a.myID、a.studentID

我有很多这样的文本文件,所以我需要一些东西来处理它,比如如果我想用空字符串替换列,它应该在替换后看起来像 从 mytable 中选择 a.myID、a.studentID

如果我想用空字符串替换 myID 它应该在替换后看起来像这样 select a.column, a.studentID from mytable

如果我想用空字符串替换 studentID 它应该是这样的 从 mytable 中选择 a.column、a.myID。

谢谢 我正在使用 C# 我正在考虑使用正则表达式,但无法提出正则表达式。

【问题讨论】:

  • 只是一个我正在尝试学习 c# 并制作一些 sql 查询并将它们输出到文本文件的副项目。只是寻找一种更好的方法来做到这一点,而无需每次都通过 giong 在文件中更改列,只需将列名传递给函数。

标签: c# sql regex


【解决方案1】:

这就是你需要的>>

using System;
using System.Text.RegularExpressions;

class Program
{
  static void Main()
  {
    string input = "select ceiling(a.interest) as interest, a.myID as mID, a.studentID as sID from mytable";
    string column = "a.myID";
    string pattern = "((?<=\\bselect)\\s+[^,]*\\b" + Regex.Escape(column) + "\\b[^,]*\\s*,?|\\s*,\\s*[^,]*\\b" + Regex.Escape(column) + "\\b[^,]*(?=(?:,|\\sfrom\\b)))";
    string output = Regex.Replace(input, pattern, "", RegexOptions.IgnoreCase);
    Console.WriteLine(output);
  }
}

测试此代码here

【讨论】:

  • 感谢您的解决方案,但我没有说清楚。我可以选择 b.portfolio, ceiling(a.interest) 作为利息,所以如果我想删除利息,它应该删除上限(a.interest) 作为利息,
  • 字符串模式 = @"((?
  • 在列中我不想说 a.myID 因为在查询中它很冷是 b.myID 或 c.myID ......我只想说 column = myID跨度>
  • @Maurh - 你是否至少用这样的列值测试过..?
  • 有一个问题,例如在您的示例中,如果您在 from 之后有一个逗号并尝试替换 studentID,它将删除该逗号之前的所有内容
【解决方案2】:

如果您想在 C# 中使用正则表达式“在选择后替换任何内容,直到下一个逗号”,以下操作将起作用:

Regex.Replace("select a.myID, a.studentID from mytable", @"select\s[^\,]+", "select newColumn");

但是,如果您需要保留表名/别名,您可能需要稍微修改一下:

Regex.Replace("select a.myID, a.studentID from mytable", @"select\s([^\.]+\.)[^\,]+", "select $1newColumn");

【讨论】:

    猜你喜欢
    • 2019-12-07
    • 2018-05-19
    • 2019-03-21
    • 2023-04-08
    • 2011-07-01
    • 1970-01-01
    • 2011-11-19
    • 2013-04-10
    • 2021-12-04
    相关资源
    最近更新 更多