我想要一个正则表达式,如果它有 3 个实例,它就做一件事.
在字符串中,如果它有超过 3 个实例,则为其他内容。
例如
aaa.bbb.ccc.ddd // one part of the regex
aaa.bbb.ccc.ddd.eee // the second part of the regex
我如何实现这一点js
or c#
?
就像是
?(\.){4} then THIS else THAT
在正则表达式中...
Update
好吧,基本上我正在做的是这样的:
我想切换,对于任何给定的System.Uri
,到扩展方法中的另一个子域。
我遇到的问题是我的域通常采用以下形式http://subdomain.domain.TLD.TLD/more/url
,但有时,它可能只是http://domain.TLD.TLD/more/url
(这只是指向www
)
所以这就是我想出的:
public static class UriExtensions
{
private const string TopLevelDomainRegex = @"(\.[^\.]{2,3}|\.[^\.]{2,3}\.[^\.]{2,3})$";
private const string UnspecifiedSubdomainRegex = @"^((http[s]?|ftp):\/\/)(()([^:\/\s]+))(:([^\/]*))?((?:\/)?|(?:\/)(((\w+)*\/)([\w\-\.]+[^#?\s]+)(\?([^#]*))?(#(.*))?))?$";
private const string SpecifiedSubdomainRegex = @"^((http[s]?|ftp):\/\/)(([^.:\/\s]*)[\.]([^:\/\s]+))(:([^\/]*))?((?:\/)?|(?:\/)(((\w+)*\/)([\w\-\.]+[^#?\s]+)(\?([^#]*))?(#(.*))?))?$";
public static string AbsolutePathToSubdomain(this Uri uri, string subdomain)
{
subdomain = subdomain == "www" ? string.Empty : string.Concat(subdomain, ".");
var replacement = "$1{0}$5$6".FormatWith(subdomain);
var spec = Regex.Replace(uri.Authority, TopLevelDomainRegex, string.Empty).Distinct().Count(c => c == '.') != 0;
return Regex.Replace(uri.AbsoluteUri, spec ? SpecifiedSubdomainRegex : UnspecifiedSubdomainRegex, replacement);
}
}
基本上用这段代码我采取System.Uri
and:
- 只取
subdomain.domain.TLD.TLD
使用Authority
财产。
- 将其与“伪 TLD”进行匹配(我永远不会拥有一个包含 2-3 个字母的注册域名,这会破坏正则表达式,它基本上会检查以
.XX[X]
or .XX[X].XX[X]
)
- 我剥离了 TLD,最终得到以下任一结果:
domain
or subdomain.domain
- 如果结果数据有零点,我使用
UnspecifiedSubdomainRegex
,因为我不知道如何使用SpecifiedSubdomainRegex
告诉它如果该部分没有点,它应该返回string.Empty
我的问题是是否有办法将这三个正则表达式合并成更简单的东西
PD:忘记 javascript,我只是用它来动态测试正则表达式