如何使用正则表达式解析属性

时间:2012-10-18 06:51:26

标签: java regex properties-file

我有一个属性文件(myfile.prop),其属性如:

name=sara
address=${this.address}
this.address=Bangalore
url=${abc}/${cde}
abc=lolkata
cde=florida
nested=${${this.work}.file}
this.work=engg
engg.file=mywork

我需要解析这些属性,以便每次获得解析后的值。

代码是:

static String resolve(String str, Properties props, boolean isResolved)
   {
      if (props == null || str == null)
      {
         return str;
      }

      String expandedString = str;
      String macroPattern   = "(\\$\\{)([a-z.\\-A-Z0-9_]*)(\\})";   
      Pattern pattern       = Pattern.compile(macroPattern);
      Matcher m             = null;
      boolean pendingItems  = true;

      do
      {
         m = pattern.matcher(expandedString);
         pendingItems = false;
         String formerStr = expandedString;

         while (m.find())
         {
            pendingItems   = true;
            String propVal = (String)props.get(m.group(2));
            if (propVal == null)
            {
               propVal = m.group(0);
            }
            expandedString = expandedString.replace(m.group(0), propVal);

            if (!fullyResolve)
            {
               return expandedString;
            }
         }
         m.reset();

         /* if the string did not change at all, it is a sign that this
          * string cannot be resolved, just return */
         if (expandedString.equals(formerStr))
         {
            return expandedString;
         }
      }
      while (pendingItems);

      return expandedString.trim();
   }

但它正在做的就是返回值....有人可以告诉我它有什么问题吗?

1 个答案:

答案 0 :(得分:1)

从Apache Commons Lang看一下StrSubstitutor

BTW,我想,使用正则表达式并不是最有效的目的。