簡體   English   中英

正則表達式IsMatch表達式

[英]Regex.IsMatch expression

什么可能是確切的Regex.IsMatch表達式

span[class|align|style]

我嘗試了這個,但我沒有得到確切的預期結果

if (!Regex.IsMatch(n.Value, @"span\[.*?style.*?\]", RegexOptions.IgnoreCase))  
    n.Value = Regex.Replace(n.Value, @"(span\[.*?)(\])", "$1" + ValToAdd + "$2");

我正在檢查span是否包含'style'元素,如果存在,則'style'將不會插入'span',反之亦然。

有指針嗎?

您忘記添加| 在ValToAdd之前。

if (!Regex.IsMatch(n.Value, @"span\[.*?\bstyle\b.*?\]", RegexOptions.IgnoreCase))  
    n.Value = Regex.Replace(n.Value, @"(span\[.*?)\]", "$1|" + ValToAdd + "]");

另外,您的第一個正則表達式將匹配span[class|align|somestyle] 使用單詞邊界\\b匹配整個單詞。 請注意,這仍然會匹配span[class|align|some-style]因為\\b在非單詞字符前后匹配。 以下正則表達式僅匹配由[|包圍的那些style s || |]

@"span\[.*(?<=\||\[)style(?=\||\[).*\]"

盡管我喜歡正則表達式,但是如果您經常在程序中執行此操作,那么使用小類來表示令牌會更好。 考慮一下這是一個粗略的草圖:

public class SamToken
{
    public string Head { get; set; }
    private readonly HashSet<string> properties;
    public HashSet<string> Properties{
        get{return properties; }
    }

    public SamToken() : this("") { }

    public SamToken(string head)
    {
        Head = head;
        properties = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
    }

    public void Add(params string[] newProperties)
    {
        if ((newProperties == null) || (newProperties.Length == 0))
            return;
        properties.UnionWith(newProperties);
    }

    public override string ToString()
    {
        return String.Format("{0}[{1}]", Head,
            String.Join("|", Properties));
    }
}

接下來,您可以使用函數從字符串中的某行中解析令牌:

public static SamToken Parse(string str)
{
    if (String.IsNullOrEmpty(str))
        return null;
    Match match = Regex.Match(str, @"^(\w*)\[([\w|]*)\]$");
    if (!match.Success)
        return null;
    SamToken token = new SamToken(match.Groups[1].Value);
    token.Add(match.Groups[2].Value.Split('|'));
    return token;
}

使用這樣的東西,可以很容易地添加屬性:

SamToken token = SamToken.Parse("span[hello|world]");
token.Add("style", "class");
string s = token.ToString(); 

如您所見,我只花了幾分鍾,但是您的代碼可以更健壯,更重要的是可重用。 您不必每次要檢查或添加屬性時都重寫該正則表達式。

暫無
暫無

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

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