2017-07-19 25 views
-4

我的目標是找到開始和結束圖案,並從長長的一串我嘗試寫C#

{BEGIN:781}{hopi_docgen4}{sub_chronic_conditions_hpi}{END:}{OPh_cc_docgen}{END:621}{BEGIN:768}{cc_reviewed} {cc_rev_prov}{END:768} 

必至REGx應滿足本=> 的開始和結束,隨後將其刪除正則表達式通過一個完整的冒號,然後其次是整數,所有這些花括號括起來像這樣{},這必須正常工作的情況下,不論

{Begin:100} or {end:112} or {BEGIN:105} or {END:398} 

目前我的解決辦法是這樣的

\b{begin:[0-1][0-1][0-1]}\b 
+0

到目前爲止您嘗試過什麼?看起來像一個家庭作業。我們不是來做你的功課。 –

+0

在發佈指南中(請在發佈之前閱讀)「提出作業幫助的問題必須包括迄今爲止解決問題所做的工作摘要,以及描述您解決問題的難度。」 – garethb

+0

This是我的第一個正則表達式實驗,這就是爲什麼我沒有把它 \ b {begin:[0-1]} \ b –

回答

1

你可以使用一個單一的正則表達式替換:

public string FindMacroType(string sentence) 
{ 
    return Regex.Replace(sentence, @"(?i){(?:END|BEGIN):[0-9]{3}}", ""); 
} 

regex demo

圖案的詳細資料

  • (?i) - 不區分大小寫修改
  • { - 文字{(不需要逃跑,但你可能)
  • (?:END|BEGIN) - 無論是endbegin
  • : - 冒號
  • [0-9]{3} - 3 ASCII數字(如果可以有1個或多個數字,只需用+量化符替換{3}限定量詞,即匹配1次或多次出現的量詞)
  • } - 字面}(不需要轉義)。
+0

非常感謝..... 我的upvote是爲了詳細的解釋。 –

-1

在我看來,正則表達式已經過時了。它只能在字符串方法不起作用或變得太複雜時使用。在這種情況下,我認爲一個字符串方法更好:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Text.RegularExpressions; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string input = "{BEGIN:781}{hopi_docgen4}{sub_chronic_conditions_hpi}{END:}{OPh_cc_docgen}{END:621}{BEGIN:768}{cc_reviewed} {cc_rev_prov}{END:768}"; 
      string output = RemovePattern(input, 781); 
     } 

     static string RemovePattern(string input, int id) 
     { 
      string output = ""; 
      string beginPattern = string.Format("{0}BEGIN:{1}{2}", "{", id.ToString(), "}"); 
      string endPattern = string.Format("{0}END:{1}{2}", "{", id.ToString(), "}"); 


      int beginIndex = input.IndexOf(beginPattern); 
      int endIndex = input.IndexOf(endPattern); 
      if (endIndex == -1) 
      { 
       endPattern = "{END:}"; 
       endIndex = input.IndexOf(endPattern, beginIndex); 
      } 
      int lengthEnd = endPattern.Length; 
      if ((beginIndex >= 0) && (endIndex >= 0)) 
      { 
       int stringLength = (endIndex + lengthEnd) - beginIndex; 

       output = input.Substring(0, beginIndex) + input.Substring(endIndex + lengthEnd); 

      } 

      return output; 
     } 
    } 
} 
+0

對不起,這根本不起作用;我們不知道int id的原因。 這就是爲什麼我們需要一個正則表達式 –

+0

然後你可以在RemovePattern方法中使用Regex來獲得END。有時需要字符串和正則表達式的混合。我並不反對正則表達式,但它不像字符串方法那樣高效。 – jdweng

+0

我不確定最初是否缺少索引是一個錯字。修復了缺少索引的代碼。假設失蹤指數是BEGIN之後的第一個END。 – jdweng

0

感謝所有的負面投票; 我找到了我的答案;

public string FindMacroType(string sentence) 
{ 

    Regex begin = new Regex(@"(\{)(BEGIN\:)[0-9][0-9][0-9](\})",RegexOptions.IgnoreCase); 
    sentence = begin.Replace(sentence,""); 

    Regex end = new Regex(@"(\{)(END\:)[0-9][0-9][0-9](\})", RegexOptions.IgnoreCase); 
    sentence = end.Replace(sentence, ""); 

    return sentence; 
} 
+0

代碼僅在其原始字符串中的第一個BEGIN/END時替換該字符串。我的代碼替換任何塊。 – jdweng