[英]how to write a regex to match characters separated by 3 slashes?
any string could be inside amongst the slashes, but there must be only 3 divisions.斜线之间可以有任何字符串,但必须只有 3 个分区。 For instance, Values that should match:例如,应匹配的值:
Values that should not match:不应该匹配的值:
I am using python and the re library, I have tried lots of combination but none of them worked:我正在使用 python 和 re 库,我尝试了很多组合,但都没有奏效:
bool(re.match(r'^.*\/.*\/.*\/((?!\/).)*$', "90/90/90/9090/90"))
bool(re.match(r'^.*\/.*\/.*\/((?!/).)*$', "90/90/90/9090/90"))
bool(re.match(r'^.*\/.*\/.*\/(?!(/)$).*$', "90/90/90/9090/90"))
bool(re.match(r'^.*\/.*\/.*\/(/).*$', "90/90/90/90/90"))
bool(re.match(r'^.*\/.*\/.*\/.*(\/)$', "90/90/90/90/90"))
You ought to use negated character classes :您应该使用否定字符类:
^[^/]*/[^/]*/[^/]*/[^/]*$
[^/]
matches any character but /
, so we represent a string that contains three /
and anything else around them. [^/]
匹配除/
任何字符,因此我们表示一个包含三个/
以及它们周围的任何其他字符的字符串。
In your regexes, the .
在您的正则表达式中, .
could match anything including /
, and while you could have approximated an equivalent of negated character classes using negative lookarounds, you didn't properly apply them to every .
可以匹配包括/
在内的任何内容,虽然您可以使用否定查找来近似等效的否定字符类,但您没有正确地将它们应用于每个.
you had : ^((?!\\/).)*\\/((?!\\/).)*\\/((?!\\/).)*\\/((?!\\/).)*$
would have worked too, although it would have been less performant.你有: ^((?!\\/).)*\\/((?!\\/).)*\\/((?!\\/).)*\\/((?!\\/).)*$
也会起作用,尽管它的性能会降低。
And there's no need to escape those /
, they aren't regex meta-characters.并且没有必要转义那些/
,它们不是正则表达式元字符。 You might need to escape them in languages or tools that use /
as delimiters, such as JavaScript's /pattern/
syntax or sed's s/search/replace/
substitutions.您可能需要在使用/
作为分隔符的语言或工具中对它们进行转义,例如 JavaScript 的/pattern/
语法或 sed 的s/search/replace/
替换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.