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:
String.StartsWith("mailto:")
String.StartsWith("ftp")
It looks like a regex would be better for this. Or is there a C# way I am missing here?
I really recommend using the String.StartsWith method over the Regex.IsMatch if you only plan to check the beginning of a string.
In your case you should use regular expressions only if you plan implementing more complex string comparison in the future.
For the extension method fans:
public static bool RegexStartsWith(this string str, params string[] patterns)
{
return patterns.Any(pattern =>
Regex.Match(str, "^("+pattern+")").Success);
}
Usage
var answer = str.RegexStartsWith("mailto","ftp","joe");
//or
var answer2 = str.RegexStartsWith("mailto|ftp|joe");
//or
bool startsWithWhiteSpace = " does this start with space or tab?".RegexStartsWith(@"\s");
The StartsWith method will be faster, as there is no overhead of interpreting a regular expression, but here is how you do it:
if (Regex.IsMatch(theString, "^(mailto|ftp|joe):")) ...
The ^
mathes the start of the string. You can put any protocols between the parentheses separated by |
characters.
Another approach that is much faster, is to get the start of the string and use in a switch. The switch sets up a hash table with the strings, so it's faster than comparing all the strings:
int index = theString.IndexOf(':');
if (index != -1) {
switch (theString.Substring(0, index)) {
case "mailto":
case "ftp":
case "joe":
// do something
break;
}
}
The following will match on any string that starts with mailto
, ftp
or http
:
RegEx reg = new RegEx("^(mailto|ftp|http)");
To break it down:
^
matches start of line(mailto|ftp|http)
matches any of the items separated by a |
I would find StartsWith
to be more readable in this case.
Source: Stackoverflow.com