简体   繁体   English

正则表达式,用于匹配以模式开头但不以模式结尾的字符串

[英]Regex for matching a string starting with a pattern and not ending with a pattern

Given a url, i have to match that the url starts with certain domain and not ends with certain pattern. 给定一个URL,我必须匹配该URL以特定域开头而不以特定模式结尾的情况。
For eg, 例如
Given a list of urls i want to match a url that starts with "http://www.google.com/" or "http://www.facebook.com/" and not ends with ".jpg" and ".bmp" and ".png" 给定一个URL列表,我想匹配一个以"http://www.google.com/""http://www.facebook.com/"开头但不以".jpg"".bmp"结尾的url ".bmp"".png"

I tried something like 我尝试了类似的东西

^(http://www\.google\.com/|http://www\.facebook\.com/).*(\.(?!png)|(?!bmp)|(?!jpg))$

But it doesn't seem to work.. Any Mistakes in it? 但这似乎不起作用。有任何错误吗? Or Any alternate way? 还是任何其他方式?

Something like (?!png)$ is, in general, pretty meaningless; 一般而言, (?!png)$类的东西是毫无意义的。 it means "a position that is not followed by png , and that is at the end of the string", but of course the end of a string is never followed by png anyway, so (?!png)$ is equivalent to just $ . 它的意思是“后面没有一个位置png ,那就是在字符串的结束”,但当然一个字符串的结尾永远不会其次png无论如何,所以(?!png)$仅相当于$ (Do you see what I mean?) (你明白我的意思吗?)

Java regexes, fortunately, support zero-width lookbehind assertions, so you can write: 幸运的是,Java正则表达式支持零宽度后断言,因此您可以编写:

^http://www\.(google|facebook)\.com.*(?<!\.(png|bmp|jpg))$

where (?<!...) means "a position that is not preceded by ... ". 其中(?<!...)意思是“一个不以... 开头的位置”。 (See the Javadoc for java.util.regex.Pattern .) (请参阅Javadoc中的java.util.regex.Pattern 。)

This regex should work: 这个正则表达式应该工作:

^https?:\/\/(?:www\.)?(?:google|facebook)\.com\/(?!.*?\.(?:jpe?g|png|bmp|gif)$).*$

Live Demo: http://www.rubular.com/r/V0X6ve1iUT 现场演示: http//www.rubular.com/r/V0X6ve1iUT

Java Demo: http://ideone.com/TlCyTG Java演示: http//ideone.com/TlCyTG

试试这是您想要的确切要求

^(http://www\.google\.com/|http://www\.facebook\.com/)(?!.*?\.(?:jpe?g|png|bmp|gif)$).*$

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM