繁体   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