2017-07-19 108 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