我想要一个正则表达式,如果它.
在字符串中有3个实例,那么它会做一件事,如果它有超过3个实例则需要其他东西.
例如
aaa.bbb.ccc.ddd // one part of the regex
aaa.bbb.ccc.ddd.eee // the second part of the regex
Run Code Online (Sandbox Code Playgroud)
我怎么在这两种实现这一点js
还是c#
?
就像是
?(\.){4} then THIS else THAT
Run Code Online (Sandbox Code Playgroud)
在正则表达式内......
更新
好吧基本上我正在做的是这样的:
我希望将任何给定的切换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);
}
}
Run Code Online (Sandbox Code Playgroud)
基本上这个代码我采取System.Uri
和:
subdomain.domain.TLD.TLD
使用Authority
酒店..XX[X]
或结尾的任何内容.XX[X].XX[X]
)domain
或者subdomain.domain
UnspecifiedSubdomainRegex
,因为我无法弄清楚如何使用SpecifiedSubdomainRegex
它告诉它,如果它没有那个部分的点,它应该返回string.Empty
那么我的问题是,是否有办法将这三个正则表达式合并为更简单的东西
PD:忘了javascript,我只是用它来动态测试正则表达式
Tim*_*ker 15
您可以使用(?(?=condition)then|else)
构造执行此操作.但是,这在JavaScript中不可用(但它在.NET,Perl和PCRE中可用):
^(?(?=(?:[^.]*\.){3}[^.]*$)aaa|eee)
Run Code Online (Sandbox Code Playgroud)
例如,将检查一个字符串是否包含正好三个点,如果是,它会尝试匹配aaa
字符串的开头; 否则它会尝试匹配eee
.所以它会匹配前三个字母
aaa.bbb.ccc.ddd
eee.ddd.ccc.bbb.aaa
eee
Run Code Online (Sandbox Code Playgroud)
但失败了
aaa.bbb.ccc
eee.ddd.ccc.bbb
aaa.bbb.ccc.ddd.eee
Run Code Online (Sandbox Code Playgroud)
说明:
^ # Start of string
(? # Conditional: If the following lookahead succeeds:
(?= # Positive lookahead - can we match...
(?: # the following group, consisting of
[^.]*\. # 0+ non-dots and 1 dot
){3} # 3 times
[^.]* # followed only by non-dots...
$ # until end-of-string?
) # End of lookahead
aaa # Then try to match aaa
| # else...
eee # try to match eee
) # End of conditional
Run Code Online (Sandbox Code Playgroud)