使用正则表达式模式的查找表
我最近遇到了一个建议,即将我们的应用程序代码库中使用的正则表达式模式集中到一个查找表中,并从那里检索,而不是在程序逻辑中显式硬编码。
任何人都可以分享对此智慧的任何想法吗?
我最初的想法是,它使模式更容易改变,这既有优点也有缺点。但是,从根本上讲,我将正则表达式字符串本身视为(有效)执行的逻辑实体,因此将它们存储在查找表中只会让我感到有点不安。
有人想吗?
谢谢
I recently encountered a suggestion for the regex patterns utilised across our application code base to be pooled together into a lookup table, and retrieved from there rather than explicitly hard-coded within the program logic.
Can anyone share any thoughts as to the wisdom of this?
My initial thoughts were that it makes the patterns easier to change, which carries both advantages and disadvantages. But, fundamentally, I see a regex string itself as an entity of logic which is (effectively) executed, so storing them in a lookup table just makes me feel a little uneasy.
Thoughts anyone?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这是一个很好的主意,如果您设法改进正则表达式模式(或者甚至解决它的问题),您将在一个地方而不是到处更改它(可能就是这样做的动机) 。
这将减少程序中潜在错误的数量(或者增加错误的数量,如果您错误地更改了它)。但是,这“应该”几乎立即在测试中显现出来,并且您仍然只需在一处修复它,而不是到任何地方......再一次,更容易出错)。
关于将其视为逻辑实体,如果您将其视为保存在参考库中的一组指令,而不是逻辑本身,会有帮助吗?逻辑本身是由正则表达式处理器执行的,而不是由您在代码中键入的模板执行的,因此我认为它是存储在查找表中的良好候选者。
I think this is an excellent idea, If you manage to improve on a regex pattern (or even fix a problem with it), you're going to change it in a single place and not everywhere (probably the very motive for doing this).
This is going to reduce the number of potential bugs in the program (or increase them, if you change it incorrectly. However, this 'should' manifest itself almost immediately in testing and you still only have to fix it in one place, as opposed to everywhere... once again, more error-prone).
With regards to seeing it as an entity of logic, would it help if you saw it as a set of instructions that are kept in a reference library, rather than the logic itself? The logic itself is performed by the regex processor rather than the template that you have typed in code, so I see it as a fine candidate to be stored in a lookup table.
如果这会导致不必要的 SQL 连接,我会说不。不要这样做。逃到山上。
但除此之外,如果它们经常重复,请考虑如何重构您的代码。您是否应该在多个页面中包含的函数或类中使用它们?如果答案是否定的,那就继续吧,我不认为这有什么问题。
If it's going to result in otherwise unnecessary SQL connections, I would say, no. Don't do it. Flee to the hills.
But otherwise, if they're being often repeated, think about how your code can be refactored. Should you be using them in functions or classes which are included in several pages? If the answer's no, then go ahead, I don't see a problem with it.