什么是正则表达式来检查字符串是以"mailto"或"ftp"或"joe"开头还是......
现在我正在使用C#和类似的代码在一个很大的o中:
String.StartsWith("mailto:")
String.StartsWith("ftp")
Run Code Online (Sandbox Code Playgroud)
看起来像正则表达式会更好.或者我在这里缺少一种C#方式?
Mar*_*ers 60
你可以使用:
^(mailto|ftp|joe)
Run Code Online (Sandbox Code Playgroud)
但说实话,StartsWith这里完全没问题.您可以按如下方式重写它:
string[] prefixes = { "http", "mailto", "joe" };
string s = "joe:bloggs";
bool result = prefixes.Any(prefix => s.StartsWith(prefix));
Run Code Online (Sandbox Code Playgroud)
System.Uri如果要解析URI,也可以查看该类.
Ode*_*ded 19
以下内容将匹配以任何字母开头的字符串mailto,ftp或http:
RegEx reg = new RegEx("^(mailto|ftp|http)");
Run Code Online (Sandbox Code Playgroud)
要打破它:
^ 匹配行的开头(mailto|ftp|http) 匹配由a分隔的任何项目 |StartsWith在这种情况下,我会发现更具可读性.
StartsWith方法会更快,因为没有解释正则表达式的开销,但这是你如何做到的:
if (Regex.IsMatch(theString, "^(mailto|ftp|joe):")) ...
Run Code Online (Sandbox Code Playgroud)
将^字符串的开头匹配.您可以在括号之间放置由|字符分隔的任何协议.
另一种更快的方法是获取字符串的开头并在开关中使用.交换机使用字符串设置哈希表,因此它比比较所有字符串更快:
int index = theString.IndexOf(':');
if (index != -1) {
switch (theString.Substring(0, index)) {
case "mailto":
case "ftp":
case "joe":
// do something
break;
}
}
Run Code Online (Sandbox Code Playgroud)