How to find everything that is not matching a regular expression

早过忘川 提交于 2019-12-11 05:24:33

问题


I would like to search all over thousands of HTML code for bad practice of height, width or any other CSS.

for instance I would like to get all places where height is not provided with units, for instance height:40 should be found, but height:40px shouldn't.

For that I am using the search program agent ransack, in which I can put regular expression to search within files.

Currently my regular expression is:

(height:)[\s]*[0-9]*\.?[0-9]+(px) 

this finds everything that is like height:40px. (Later on I want to add width, or other things)

My question is how to make a NOT on top of all that?

Or is there any other good application to search files for regular expressions?


回答1:


Use a negative lookahead (?!regex), eg:

height:\s*\d+(?:\.\d+)?(?!px|\d)

\d is needed to prevent backtracking alternatives from matching.




回答2:


Consider using a program that already does this, and add you own rules. In general, the practice of fixing up source code is called 'linting'. So, you can find quickly something like CSSLint which is open source and allows custom rules:

https://github.com/stubbornella/csslint/wiki/Rules

http://csslint.net/




回答3:


Use the negative lookahead this way:

(?!height:\s*\d+(?:\.\d+)?px)height:\s*\d+(?:\.\d+)?

Considering you are using css, you may want to include other units as valid ones like pt, em, %, etc... like the below regex

(?!height:\s*\d+(?:\.\d+)?(?:px|pt|em|%|cm|mm|in|ex|pc))height:\s*\d+(?:\.\d+)?

You can test it over Rubular



来源:https://stackoverflow.com/questions/12284037/how-to-find-everything-that-is-not-matching-a-regular-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!