簡體   English   中英

如何用正則表達式構造它

[英]How to construct this in regular expression

我要匹配模式:以0或多個空格開頭,后跟“ ABC”,然后再跟任何東西。

因此,將匹配" ABC " " ABC111111" "ABC"
但是不會匹配" AABC" "SABC"

我試過了:

String Pattern = "^\\s*ABC(.*)";

但這行不通。

有任何想法嗎? 順便說一下,這是在C#中。

嘗試

string pattern = @"\s*ABC(.*)"; // Using @ makes it easier to read regex. 

我已驗證這在regexpl.com上有效

\\\\通常放在文字反斜杠中,因此這可能是解決方案失敗的地方。 除非進行替換,否則不需要.*周圍的括號.*

\\s還會匹配空格字符[ \\t\\n\\f\\r\\x0B]或空格,制表符,換行符,換頁符,返回符和垂直制表符之外的字符。

我會建議:

String Pattern = @"^[ ]*ABC.*$";  

我測試了這個。 有用。 如果只想匹配大寫ABC,則可以省略RegexOptions.IgnoreCase。

/// <summary>
/// Gets the part of the string after ABC
/// </summary>
/// <param name="input">Input string</param>
/// <param name="output">Contains the string after ABC</param>
/// <returns>true if success, false otherwise</returns>
public static bool TryGetStringAfterABC(string input, out string output)
{
    output = null;

    string pattern = "^\\s*ABC(?<rest>.*)";

    if (Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase))
    {
        Regex r = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
        output = r.Match(input).Result("${rest}");
        return true;
    }
    else
        return false;
}

調用代碼:

static void Main(string[] args)
{
    string input = Console.ReadLine();

    while (input != "Q")
    {
        string output;
        if (MyRegEx.TryGetStringAfterABC(input, out output))
            Console.WriteLine("Output: " + output);
        else
            Console.WriteLine("No match");
        input = Console.ReadLine();
    }
}

確保已將正則表達式引擎設置為使用SingleLine而不是MultiLine。

暫無
暫無

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

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