C#正则表达式

问题描述:

我需要一个正则表达式来从基于索引的文本输入中获取单词。这个词应该放在括号内。C#正则表达式

我会尽量通过举例来解释。 如果我的输入是hh{jhh}jkhjh{jkjhh{kljk}j}adajskjj}。对于任何字符索引,如果它位于一对括号之间,我必须提取包含括号的单词。 在上面的输入中,如果索引是2或4,输出应该是{jhh}

+0

应该发生什么? –

+1

您的括号似乎无法正确打开和关闭,这是故意的吗? – svick

+0

如果索引是14,因为没有关联的括号不存在,它将不会返回任何内容。 – Naresh

试试这个。当然有很多问题。首先,你没有说你想如何处理嵌套的括号。如果你需要处理嵌套的括号,那么你用简单的正则表达式运气不好,因为你需要一个上下文无关的语法。还要注意,以下实现是天真的,因为它在查找单词时具有线性时间复杂度(查找单词的时间与找到的匹配数成正比)。然而,这对大量的比赛来说只是一个问题。更好的实现可以使用例如排序的匹配数组和二进制搜索进行查找。

using System.Text.RegularExpressions; 

namespace WindowsFormsApplication1 
{ 
    public class ParsedInput 
    { 
     public static readonly Regex RegularExpression = new Regex("{[a-z]*}"); 

     private MatchCollection matches; 

     public ParsedInput(string input) 
     { 
      matches = RegularExpression.Matches(input); 
     } 

     public bool TryGetWord(int index, out string word) 
     { 
      foreach (Match match in matches) 
      { 
       if (index >= match.Index && index < (match.Index + match.Length)) 
       { 
        word = match.Captures[0].Value; 
        return true; 
       } 
      } 

      word = ""; 
      return false; 
     } 
    } 
} 

要使用,做到:

var parsed = new ParsedInput(input); 
string word = ""; 

if (parsed.TryGetWord(index, out word)) 
{ 
    // A word exists at the given index, do something. 
} 
else 
{ 
    // Handle missing word at the given index (optional). 
} 

不知道你在问什么,正则表达式是正则表达式,你不能告诉它开始从索引i看,也向后移动搜索。你要找

正则表达式可能是这样的:

(\{.*\}) 

如果你正在寻找一种方式来获得只是那些群里开始>指数<结束时,我可能会捕获所有组,然后遍历通过它们来检查索引是否在开始和结束之间。

我认为这是最好的使用正则表达式这一点,因为这是非常特殊的,图案是不是通用的就够了(缺少括号例如)

写自己的分词来代替。

你的规格是相当短暂的,但这样的事情可能会是比 正则表达式更好。

string GetWord(string value, int index) 
{ 
    if (index < 0 || index >= value.Length) 
    { 
     return String.Empty; 
    } 
    int start = (value[index] == '}') ? index-1 : index; 
    int end = (value[index] == '}') ? index : index+1; 
    int count = 1; 
    for (; start >= 0 && count > 0; start--) 
    { 
     count += (value[start] == '}') ? 1 : 0; 
     count -= (value[start] == '{') ? 1 : 0; 
    } 
    for (count = 1; end < value.Length && count > 0; end++) 
    { 
     count += (value[end] == '{') ? 1 : 0; 
     count -= (value[end] == '}') ? 1 : 0; 
    } 
    return value.Substring(++start, end - start); 
} 

输出,用于测试的字符串将是:如果该指数为14

GetWord(input,2) == "{jhh}" 
GetWord(input,8) == "hh{jhh}jkhjh{jkjhh{kljk}j}adajskjj}" 
GetWord(input,14) == "{jkjhh{kljk}j}" 
GetWord(input,30) == "hh{jhh}jkhjh{jkjhh{kljk}j}adajskjj}" 
GetWord(input,99) == ""