因为如果一个字符串具有一定的子开始检查正则表达式? [英] Regex pattern for checking if a string starts with a certain substring?

查看:128
本文介绍了因为如果一个字符串具有一定的子开始检查正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个字符串电子邮件地址或FTP或乔或...

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

现在我使用C#和code这样的一个大的,如果有许多ORS:

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

String.StartsWith("mailto:")
String.StartsWith("ftp")

它看起来像一个正则表达式将是这更好的。或者是有一个C#的方式,我在这里丢失?

It looks like a regex would be better for this. Or is there a C# way I am missing here?

推荐答案

您可以使用:

^(mailto|ftp|joe)

不过说实话, StartsWith 是完全没有到这里。可以按如下方式重写它:

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));

您也可以看一下 的System.Uri 类,如果你正在分析的URI。

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

这篇关于因为如果一个字符串具有一定的子开始检查正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆