不应该是“静态的”模式永远是静态的? [英] Shouldn't "static" patterns always be static?

查看:86
本文介绍了不应该是“静态的”模式永远是静态的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚发现了一些我没写过的代码中的错误,我有点惊讶:

I just found a bug in some code I didn't write and I'm a bit surprised:

Pattern pattern = Pattern.compile("\\d{1,2}.\\d{1,2}.\\d{4}");
Matcher matcher = pattern.matcher(s);

尽管此代码在输入数据上严重失败,但我们得到(因为它试图找到17.01.2011格式的日期并找回10396/2011之类的内容然后崩溃,因为它无法解析日期但真的不是这个问题的重点;)我想知道:

Despite the fact that this code fails badly on input data we get (because it tries to find dates in the 17.01.2011 format and gets back things like 10396/2011 and then crashed because it can't parse the date but that really ain't the point of this question ; ) I wonder:


  • 不是 Pattern.compile 的重点之一速度优化(通过预编译正则表达式)?

  • isn't one of the point of Pattern.compile to be a speed optimization (by pre-compiling regexps)?

不应该将所有静态模式始终编译成静态模式吗?

shouldn't all "static" pattern be always compiled into static pattern?

网上有很多例子,总是使用 Pattern重新编译相同的模式.compile 我开始怀疑自己是否看到了什么。

There are so many examples, all around the web, where the same pattern is always recompiled using Pattern.compile that I begin to wonder if I'm seeing things or not.

不是(假设字符串是静态的,因此不是动态构造的):

Isn't (assuming that the string is static and hence not dynamically constructed):

static Pattern pattern = Pattern.compile("\\d{1,2}.\\d{1,2}.\\d{4}");

总是优先于非静态模式参考?

always preferrable over a non-static pattern reference?

推荐答案


  1. 是的,预先编译模式的全部意义只是做它一次。

  2. 这实际上取决于你将如何使用它,但一般来说,存储在 static 中的预编译模式字段应该没问题。 (与 Matcher 不同,它们不是线程安全的,因此根本不应该存储在字段中,静态或不存在。)

  1. Yes, the whole point of pre-compiling a Pattern is to only do it once.
  2. It really depends on how you're going to use it, but in general, pre-compiled patterns stored in static fields should be fine. (Unlike Matchers, which aren't threadsafe and therefore shouldn't really be stored in fields at all, static or not.)

在静态初始化器中编译模式的唯一警告是,如果模式没有编译并且静态初始化器抛出异常,则错误的来源可能非常烦人。追查。这是一个小的可维护性问题,但值得一提。

The only caveat with compiling patterns in static initializers is that if the pattern doesn't compile and the static initializer throws an exception, the source of the error can be quite annoying to track down. It's a minor maintainability problem but it might be worth mentioning.

这篇关于不应该是“静态的”模式永远是静态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆