簡體   English   中英

使用文檔中的字符串的.Net AND運算符正則表達式

[英].Net AND operator Regular Expression using strings in a document

假設我有一種情況,我需要在文檔中搜索“ Foo”一詞,但僅在單詞“ Bar”出現在該文檔的其他任何地方時才希望它匹配(即“ Bar”可以在同一行,在“ Foo”之前或之后的另一行)。 我可以使用正則表達式來做到這一點嗎?

按照 SE帖子中的鏈接,我嘗試了:

Foo(?=.*\nBar)|Foo(?=.*Bar)|Foo(?<!.*Bar)|Foo(?<!.*\nBar)

如果Foo丟失,該方法很好用,但是即使Bar缺失,它仍然選擇Foo。 我也檢查了 SE帖子,但所有答案都涉及Java / Perl,並且不能在.NET上使用。

是否可以使用.NET中的正則表達式來完成此操作,還是我需要在代碼本身中使用C#&&運算符?

如果我正確理解了您的問題,那么您的代碼幾乎是不錯的。

嘗試這個 :

    Foo(?=.*Bar)|Foo(?<=Bar.*)

它的意思是 :

Select from 2 alternatives :
    - Foo, then match a suffix (.*Bar) but exclude it from the capture
    - Foo, with a prefix (Bar.*) but exclude it from the capture

希望能幫助到你 :-)

不確定要問的內容:僅在文檔中同時包含“ foo”和“ bar”時,才要返回匹配項嗎? 如果是這樣的話

(?>.*foo.*bar)|(?>.*bar.*foo) 

效果很好。 然后在C#.Net中使用RegexOptions.Singleline,使“。” 不止於“ \\ n”。

代碼示例:

        string text = @"blah blah bar foo bar";
        string pattern = @"(?>.*foo.*bar)|(?>.*bar.*foo)";
        Match match = new Regex(pattern, RegexOptions.Singleline).Match(text);
        if (match.Success)
        {
            // do something
        }

但是,如果這就是您想要的,那么使用字符串contains方法要簡單得多。

編輯:根據您的新注釋,使用命名捕獲組來捕獲此數字,請嘗試此正則表達式:

((?<CCNum>4\d{3}[ -]?(\d{4}[ -]?){2}\d{4}).*Bar)|(.*Bar.*(?<CCNum>4\d{3}[ -]?(\d{4}[ -]?){2}\d{4}))

和用法:

        string text = @"Bar 4111-1111 1111 1111";
        string pattern = @"((?<CCNum>4\d{3}[ -]?(\d{4}[ -]?){2}\d{4}).*Bar)|(.*Bar.*(?<CCNum>4\d{3}[ -]?(\d{4}[ -]?){2}\d{4}))";
        long CCNum;
        Match match = new Regex(pattern, RegexOptions.Singleline).Match(text);
        if (match.Success)
        {
            if (Int64.TryParse (match.Groups["CCNum"].Value.Replace(" ", "").Replace("-",""),out CCNum));
            {
                // here is your clean CC Number
            }


        }

暫無
暫無

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

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