gpt4 book ai didi

c# - 如何条件正则表达式

转载 作者:太空狗 更新时间:2023-10-29 17:38:24 26 4
gpt4 key购买 nike

我想要一个正则表达式,如果它在字符串中有 3 个 . 实例,它就做一件事,如果它有超过 3 个实例,它就做其他事情。

例如

aaa.bbb.ccc.ddd // one part of the regex

aaa.bbb.ccc.ddd.eee // the second part of the regex

如何在 jsc# 中实现这一点?

有点像

?(\.){4} then THIS else THAT

在正则表达式中...

更新

好的,基本上我正在做的是:

对于任何给定的 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 和:

  1. 使用 Authority 属性仅获取 subdomain.domain.TLD.TLD
  2. 将它与“伪顶级域名”相匹配(我永远不会拥有一个包含 2-3 个字母的注册域,这会破坏正则表达式,它基本上检查以 .XX[X] 结尾的任何内容> 或 .XX[X].XX[X])
  3. 我去除了 TLD,最后得到 domainsubdomain.domain
  4. 如果结果数据有零个点,我使用 UnspecifiedSubdomainRegex,因为我不知道如何使用 SpecifiedSubdomainRegex 告诉它如果它没有点在那部分,它应该返回 string.Empty

我的问题是是否有办法将这三个正则表达式合并成更简单的东西

PD:忘记 javascript,我只是用它来动态测试正则表达式

最佳答案

您可以使用 (?(?=condition)then|else) 构造来执行此操作。但是,这在 JavaScript 中不可用(但在 .NET、Perl 和 PCRE 中可用):

^(?(?=(?:[^.]*\.){3}[^.]*$)aaa|eee)

例如,将检查一个字符串是否恰好包含三个点,如果是,它会尝试匹配字符串开头的 aaa;否则它会尝试匹配 eee。所以它会匹配的前三个字母

aaa.bbb.ccc.ddd
eee.ddd.ccc.bbb.aaa
eee

但是失败了

aaa.bbb.ccc
eee.ddd.ccc.bbb
aaa.bbb.ccc.ddd.eee

解释:

^            # 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

关于c# - 如何条件正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6804586/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com