簡體   English   中英

C#正則表達式

[英]C# Regular Expression

我需要一個正則表達式來從基於索引的文本輸入中獲取單詞。 這里的單詞應放在方括號中。

我將通過舉一個例子來解釋。 如果我的輸入是hh{jhh}jkhjh{jkjhh{kljk}j}adajskjj} 對於任何字符索引,如果它位於一對括號之間,那么我必須獲取包含括號的單詞。 在上述輸入中,如果index為2或4,則輸出應為{jhh}

不確定您要的是什么,regexp是regexp,您不能告訴它從索引i開始查找,也不能向后移動搜索。

您正在尋找的正則表達式可能是這樣的:

(\{.*\})

如果您正在尋找一種只獲取開始>索引<結束的組的方法,我可能會捕獲所有組,然后遍歷它們以檢查索引是否在開始和結束之間。

我認為最好不要使用正則表達式,因為它非常具體並且模式不夠通用(例如缺少括號)

而是編寫您自己的令牌生成器。

嘗試這個。 當然有很多問題。 首先,您沒有說要如何處理嵌套括號。 如果您需要處理嵌套的方括號,那么使用簡單的正則表達式就很不走運,因為您需要使用上下文無關的語法。 還要注意,以下實現是幼稚的,因為它在單詞查找上具有線性時間復雜度(查找單詞的時間與找到的匹配項數量成正比)。 但是,那只會是大量比賽的問題。 更好的實現方式可以使用例如匹配的排序數組和用於查找的二進制搜索。

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).
}

您的規格非常簡短,但是類似這樣的東西可能會比Regex更好。

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);
}

測試字符串的輸出為:

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) == ""

暫無
暫無

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

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