Java Regex - 更高效的动态正则表达式

时间:2016-05-02 20:26:39

标签: java regex

我有一个Regex,我依赖它来替换字符串中的变量。正则表达式本身非常有效。我对Regex编译的效率更感到困扰。基于分析,我的程序花了很多时间编译这个正则表达式,所以也许有一个更好的机制来实现我的目标。我的代码看起来有点像这样:

for(String attribute : attributes.keySet())
{
  for(String searchAttribute : searchAttributes.keySet())
  {
    attributes.put(attributes.get(attribute).replaceAll(
    "(?<![A-Za-z0-9])"+searchAttribute+"(?![A-Za-z0-9])", 
    "(" + searchAttributes.get(searchAttribute) + ")");
  }
}

attributessearchAttributes是HashMap。假设每次调用周围函数时,它们中的值是不同的。也就是说,我不能静态地为集合预编译正则表达式并完成。

这个例子有点人为,但它与我在我的程序中实际做的非常接近。有没有更快/更好的方式去做我正在做的事情?

0 个答案:

没有答案
相关问题