从字符串中排除子字符串

huangapple go评论63阅读模式
英文:

Nginx exclude substring from a string

问题

I am looking for a to exclude a substring from a string with nginx regex:

要在字符串中排除一个子字符串:

exclude a substring : toto

排除子字符串:toto

I try many example from internet, but I don't find the correct one.

我尝试了很多来自互联网的例子,但我找不到正确的。

Not matching :

不匹配:

toto.example.instance.fr
titi-toto.example.instance.fr

Matching :

匹配:

titi.example.instance.fr
titi-titi.example.instance.fr

I try this regex :

我尝试了这个正则表达式:

^((?!toto).)\.example\.instance\.fr$

but when I add example.instance.fr, it is matching nothing

但是当我添加example.instance.fr时,它什么都不匹配。

英文:

I am looking for a to exclude a substring from a string with nginx regex :

exclude a substring : toto
I try many example from internet, but I don't find the correct one.

Not matching :

toto.example.instance.fr
titi-toto.example.instance.fr

Matching :

titi.example.instance.fr
titi-titi.example.instance.fr

I try this regex :

^((?!toto).)\.example\.instance\.fr$

but when I add example.instance.fr, it is matching nothing

答案1

得分: 0

代码部分不翻译,只翻译文本内容:

你的正则表达式中的 ^((?!toto).) 部分匹配字符串开头的任意单个字符(.),但不匹配以 toto 字符序列开头的字符。然而,即使没有前瞻,toto 也不能匹配,因为在 . 部分之后,会出现 \.example\.instance\.fr$,这明确要求在与 . 匹配的单个字符之后出现 .example.instance.fr

你可以使用以下正则表达式:

^(?![^.]*toto\.)[^.]+\.example\.instance\.fr$

详细说明

  • ^ - 字符串开头
  • (?![^.]*toto\.) - 不允许以零个或多个非 . 字符后跟 toto. 字符串的方式开头
  • [^.]+ - 一个或多个非 . 字符
  • \.example\.instance\.fr$ - 匹配 .example.instance.fr 直到字符串结尾。

请参阅正则表达式演示

注意
如果需要将 toto 视为完整单词进行匹配,可以添加单词边界:

^(?![^.]*\btoto\.)[^.]+\.example\.instance\.fr$
         ^^
英文:

The ^((?!toto).) part of your regex matches any single character (.) at the start of the string (^), that does not start a toto char sequence. However, toto cannot be matched even without the lookahead, since after the . part, \.example\.instance\.fr$ comes and definitely requires .example.instance.fr to appear right after that single char matched with ..

You can use

^(?![^.]*toto\.)[^.]+\.example\.instance\.fr$

Details

  • ^ - start of string
  • (?![^.]*toto\.) - no zero or more chars other than . followed with toto. string allowed at the start
  • [^.]+ - one or more chars other than .
  • \.example\.instance\.fr$ - .example.instance.fr string till end of the string.

See the regex demo.

Note

If toto must be matched as a whole word, you can add a word boundary:

^(?![^.]*\btoto\.)[^.]+\.example\.instance\.fr$
         ^^

huangapple
  • 本文由 发表于 2023年6月26日 16:39:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76554970.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定