簡體   English   中英

如何在.NET中使用正則表達式從字符串中提取子字符串

[英]How i can extract substring from string using regular expression in .NET

我想使用正則表達式從字符串中提取子字符串。 以下輸入/輸出列表顯示了我真正想要的。 我需要從字符串中提取部過濾條件。 這里的[dept]一詞是常量。在這種情況下,什么樣的正則表達式可用於提取子字符串

    Input------------------------------------------------Output 

    Some conditions And [dept]=IT                        [dept]=IT
    Some conditions And [dept]=IT Or [dept]=Account      [dept]=IT Or [dept]=Account
    Some conditions And [dept] IN ('IT','Account')       [dept] IN ('IT','Account')

    [dept]=IT And some conditions                        [dept]=IT
    [dept]=IT Or [dept]=Account And some conditions      [dept]=IT Or [dept]=Account 
    [dept] IN ('IT','Account') And some conditions       [dept] IN ('IT','Account')

這可能與您追求的目標接近

(\[dept\]=\w+)( (Or)|(And))?|(\[dept\] IN \(.+?\))

它與您的示例輸入匹配,如下所示,在()中分組。

([dept]=IT) 
([dept]=IT Or) ([dept]=Account) 
([dept] IN ('IT','Account'))

在腳本中,您可以加入每一行的組,即加入([dept]=IT Or) ([dept]=Account)

但是,如果像注釋中所建議的那樣,您的確在解析SQL,則可以使用SQL解析器來准確訪問查詢WHERE表達式。

\[dept\].*(?=\s+\bAnd\b)|\[dept\].*(?=$)

試試看。看演示。

http://regex101.com/r/dZ1vT6/41

暫無
暫無

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

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