Regex pattern for checking if a string starts with a certain substring?

后端 未结 5 1093
小鲜肉
小鲜肉 2020-12-05 22:50

What\'s the regular expression to check if a string starts with \"mailto\" or \"ftp\" or \"joe\" or...

Now I am using C# and code like this in a big if with many ors

5条回答
  •  死守一世寂寞
    2020-12-05 23:14

    You could use:

    ^(mailto|ftp|joe)
    

    But to be honest, StartsWith is perfectly fine to here. You could rewrite it as follows:

    string[] prefixes = { "http", "mailto", "joe" };
    string s = "joe:bloggs";
    bool result = prefixes.Any(prefix => s.StartsWith(prefix));
    

    You could also look at the System.Uri class if you are parsing URIs.

提交回复
热议问题