【问题标题】:C# Regular Expression excluding a stringC# 正则表达式不包括字符串
【发布时间】:2023-03-14 17:20:02
【问题描述】:

我得到了一个字符串集合,我想要的正则表达式就是收集所有以 http.. 开头的字符串。

href="http://www.test.com/cat/1-one_piece_episodes/"href="http://www.test.com/cat/2-movies_english_subbed/"href="http:// www.test.com/cat/3-english_dubbed/"href="http://www.exclude.com"

这是我的正则表达式模式..

href="(.*?)[^#]"

并返回这个

href="http://www.test.com/cat/1-one_piece_episodes/"
href="http://www.test.com/cat/2-movies_english_subbed/"
href="http://www.xxxx.com/cat/3-english_dubbed/"
href="http://www.exclude.com"

排除最后一个匹配项的模式是什么.. 或排除具有 exclude 域的匹配项,例如 href="http://www.exclude.com"

编辑: 多重排除

href="((?:(?!"|\bexclude\b|\bxxxx\b).)*)[^#]"

【问题讨论】:

  • 您想要包含http://www.test.com/fish/exclude 的网址吗? http://www.exclude.co.ukhttp://www.exclude.test.com

标签: c# regex


【解决方案1】:

@ridgerunner 和我会将正则表达式更改为:

href="((?:(?!\bexclude\b)[^"])*)[^#]"

它匹配所有href 属性,只要它们不以# 结尾并且不包含单词exclude

说明:

href="     # Match href="
(          # Capture...
 (?:       # the following group:
  (?!      # Look ahead to check that the next part of the string isn't...
   \b      # the entire word
   exclude # exclude
   \b      # (\b are word boundary anchors)
  )        # End of lookahead
  [^"]     # If successful, match any character except for a quote
 )*        # Repeat as often as possible
)          # End of capturing group 1
[^#]"      # Match a non-# character and the closing quote.

要允许多个“禁词”:

href="((?:(?!\b(?:exclude|this|too)\b)[^"])*)[^#]"

【讨论】:

  • 解析 "href="((?:(?!"|\bexclude\b).)*[^#]"" - 还不够 ) 现在好了.. 我刚读过解释.. href="((?:(?!"|\bexclude\b).)*)[^#]"
  • 附加问题先生.. 如果我排除附加字符串 xxxx 怎么样?
  • @vrynxzent:抱歉,我已经去掉了右括号。但是您显然已经找到了正确的解决方案:)
  • +1 这个很棒的解释!我知道这样做的正则表达式编辑器,但不知何故,看着他们的输出,我总是感到困惑。你的太简洁了!
  • @ridgerunner:谢谢!我曾计划这样做,但在编写正则表达式时完全忘记了......
【解决方案2】:

您的输入看起来不像一个有效的字符串(除非您转义其中的引号),但您也可以不使用正则表达式:

string input = "href=\"http://www.test.com/cat/1-one_piece_episodes/\"href=\"http://www.test.com/cat/2-movies_english_subbed/\"href=\"http://www.test.com/cat/3-english_dubbed/\"href=\"http://www.exclude.com\"";

List<string> matches = new List<string>();

foreach(var match in input.split(new string[]{"href"})) {
   if(!match.Contains("exclude.com"))
      matches.Add("href" + match);
}

【讨论】:

    【解决方案3】:

    这样可以吗?

    href="(?!http://[^/"]+exclude.com)(.*?)[^#]"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-24
      • 2011-01-21
      • 2012-02-09
      • 1970-01-01
      • 2019-01-05
      相关资源
      最近更新 更多