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?
The startsWith() method determines whether a string begins with the characters of a specified string, returning true or false as appropriate.
The meta character “^” matches the beginning of a particular string i.e. it matches the first character of the string. For example, The expression “^\d” matches the string/line starting with a digit. The expression “^[a-z]” matches the string/line starting with a lower case alphabet.
match() function of re in Python will search the regular expression pattern and return the first occurrence. The Python RegEx Match method checks for a match only at the beginning of the string. So, if a match is found in the first line, it returns the match object.
Introduction – In bash, we can check if a string begins with some value using regex comparison operator =~ .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With