For some reason I think that regular expressions can solve every problem and for some reason I always find out the regular expression I'm trying to create is too complicated and probably not the best route to getting what I want. Case in point: I needed to create a regular expression which is meant to not match a string. I don't want to match a string which includes [requires-login] but do want to match everything else. Let's set aside the why for now, here's how I accomplished what I wanted:
由于某种原因,我认为正则表达式可以解决所有问题,并且由于某种原因,我总是发现我要创建的正则表达式过于复杂,可能不是获取所需内容的最佳途径。 举例:我需要创建一个正则表达式,该表达式不匹配字符串。 我不想匹配的字符串,其中包括[requires-login] ,但希望到别的匹配的一切。 让我们暂时搁下为什么,这是我如何实现我想要的:
// Adding extra forward slashes for "[" and "]" var regex = '^(?!.*?\\[requires-login\\])'; // Compile var re = new RegExp(regex);So why do I want to do this? Within my intern client side tests, I mark tests requiring login as [requires-login], and if a username and password aren't passed in via command line, I want to skip those tests. In that case, I leverage intern's grep function to match tests without the given string. I'd prefer to mark a few tests with [requires-login] instead of mark most of them as [no-login].
那我为什么要这样做呢? 在我的内部客户端测试中,我将需要登录的测试标记为[requires-login] ,如果没有通过命令行传递用户名和密码,我想跳过这些测试。 在那种情况下,我利用实习生的grep函数来匹配没有给定字符串的测试。 我宁愿用[requires-login]标记一些测试,而不是将大多数标记为[no-login] 。
Sometimes you want to do things within the web development world which aren't ideal but you simply need to accomplish them within a given parameter set. This is one of those cases. In the end you need to make it happen, and in this case, I did so!
有时候,您想在Web开发领域中做一些不理想的事情,而只需要在给定的参数集中完成它们即可。 这是其中一种情况。 最后,您需要实现它,在这种情况下,我做到了!
翻译自: https://davidwalsh.name/javascript-regex-string