簡體   English   中英

從單詞中刪除字符串分層直到char

[英]Remove string strats from a word until char

我有以下字符串:

customer.Id as CustomerID, case when customer.Name...

我想刪除as CustomerID從我的字符串,即與作為開頭和結尾的所有句子, 我怎樣才能做到這一點。 我和Linq一起去了,但不幸的是似乎沒有用:

select(c => c.TakeWhile(ch => ch!= 'As').SkipWhile(c=>c != ','))

如您在TakeWhileTakeWhile我可以使用char not word。 如何使用SubStringLinq或Regex做到這一點?

您可以使用

var s = "customer.Id as CustomerID, case when customer.Name...";
var res = Regex.Replace(s, @"\s+as\s+[^,]+","");
Console.WriteLine(res);
// => customer.Id, case when customer.Name...

參見C#演示

正則表達式( 請參閱演示 )是

\s+as\s+[^,]+

它匹配:

  • \\s+ -1+空格
  • as -一個字as
  • \\s+ -1+空格
  • [^,]+ - 1+比其他字符,

盡管此實現遠非完美或最簡潔,但至少可以作為一個示例,說明如何在不使用Regex的情況下完成此操作,而是使用一些帶有少量Linq的標准String API。

var queryText = "customer.Id as CustomerID, case when customer.Name...";
var columns = queryText.Split(',');
var columnsWithoutAliases = 
    from c in columns
    let indexOfAs = c.LastIndexOf(" as ")
    select indexOfAs < 0 ? c : c.Substring(0, indexOfAs);
var queryTextWithAliases = string.Join(",", columnsWithoutAliases);
string sql = "customer.Id as CustomerID, case when customer.Name...";
string sql2 = Regex.Replace(sql, @"\Was.+?(?=,)", "");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM